WAIT FOR GPIO EVENT
There will be situations when you need a program to take some sort of action when the input to a GPIO pin changes. For example, to start recording data when a switch is set, or to stop a motor when a limit switch is activated or to execute a command when a GPIO pin has zero volts on it. I have a number of headless Pis and use this program, together with a push button switch on each Pi, to shut them down quickly and in a controlled fashion when I have no SSH session open. The program described here waits for a HIGH signal on a GPIO pin (the switch closing) and then executes a pre-determined command.
The circuit diagram shows the GPIO pin connected to 0V (GND) by a 10kΩ pull-down resistor - this just keeps the pin at 0V and stops it floating and potentially triggering the action inadvertently. The 3V3 is connected to the same GPIO pin through a 330Ω resistor and the push button. When the button is pressed it connects 3V3 to the GPIO pin and the program detects this and triggers the specified action.
The Pi uses 3V3 on its GPIO pins and you must not connect the 5V supply.
When the program starts it sets up the requested GPIO pin for input and reads the pin's value file. If it reads a 1 (HIGH) from the file it executes the command, which in this case is sudo shutdown -h now.
You can set up the Pi to run the program as part of its startup sequence. The command to wait for a HIGH on GPIO pin 12 and to execute sudo shutdown -h now would be:
sudo ./waitgpio gpio12 "sudo shutdown -h now"
In the screen shot below I have logged on remotely using SSH and started the program running. It sets up GPIO pin 7 and then waits for a HIGH signal on that pin. When I trigger the action by setting GPIO pin 7 high, the system executes the command and you can see the shutdown and disconnection messages.