I have a raspberry pi 4 with the Witty Pi4 hat. I want the Witty to listen to GPIO pin 21, if it goes HIGH then turn on the raspberry, when it goes low turn raspberry off.
I've asked chatgpt for help, but don't think it really knows the answer. And as I suspected there isn't any command called poweron_witty or shutdown_witty.
This is what it has given me:
import RPi.GPIO as GPIO
import subprocess
GPIO.setmode(GPIO.BCM)
GPIO.setup(21, GPIO.IN)
try:
while True:
input_state = GPIO.input(21)
if input_state == GPIO.HIGH:
subprocess.run(["sudo", "poweron_witty"])
elif input_state == GPIO.LOW:
subprocess.run(["sudo", "shutdown_witty"])
except KeyboardInterrupt:
GPIO.cleanup()
Most probably you will need extra hardware to make it work. It is easy to listen to GPIO-21 and shutdown your Pi when it is LOW; but when your Pi is off, there is no program can run in your Pi and listen to GPIO-21 anymore.
There is indeed no "poweron_witty" and "shutdown_witty" command. The answer from ChatGPT does give you an idea though, basically it is polling the state of GPIO-21 and calls the command accordingly.
Although there is no "shutdown_witty" command, you can shutdown your Pi with "sudo shutdown -h now" command.
However turning on your Pi can not be done this way: when your Pi is off, this polling program is not running and it can do nothing. Instead you will need to schedule a startup, or use an external cirtuit to momentary short GPIO-4 to GND (equals to tapping the button) to turn on your Pi.
@admin That's what I thought. Couldn't quite imagine that a script located on the raspberry could be running when it's off.
Another solution I have come up with. Connect a relay to the solder points for the on/off button. When the relay is triggered, it will be as if you are tapping the button to turn it on and off. Would that have worked?
@wittynoob That is one way to do the "short GPIO-4 to GND". Make sure your relay only triggered for a short moment - if your relay keeps connected, that is the same as press and hold the button and Witty Pi will eventually cut the power.