How it works...

This time, when we set up the GPIO pin, we define the pin connected to the shutdown button as an input and the pin connected to the LED as an output. We turn the LED on to indicate that the system is running.

By setting the DEBUG flag to True, we can test the functionality of our script without causing an actual shutdown (by reading the terminal messages); we just need to ensure that we set DEBUG to False when using the script for real.

We enter a while loop and check the pin every second to see whether the GPIO pin is set to LOW (that is, to check whether the switch has been pressed); if so, we enter the doShutdown() function.

The program will wait for three seconds and then test again to see whether the button is still being pressed. If the button is no longer being pressed, we return to the previous while loop. However, if it is still being pressed after three seconds, the program will flash the LED and trigger the shutdown (and also provide an audio warning using flite).

When we are happy with how the script is operating, we can disable the DEBUG flag (by setting it to False) and add the script to crontab. crontab is a special program that runs in the background and allows us to schedule (at specific times, dates, or periodically) programs and actions when the system is started (@reboot). This allows the script to be started automatically every time the Raspberry Pi is powered up. When we press and hold the shutdown button for more than three seconds, it safely shuts down the system and enters a low power state (the LED switches off just before this, indicating that it is safe to remove the power shortly after). To restart the Raspberry Pi, we briefly remove the power; this will restart the system, and the LED will light up when the Raspberry Pi has loaded.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset