I am trying to trigger my Raspberry Pi to shutdown on the rising edge of GPIO #4. I ultimately want to auto run this script on startup.
My python code is in file test1.py @ /home/pi
#!/usr/bin/python
print("Starting")
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(4, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.add_event_detect(4, GPIO.RISING)
def my_callback(x):
print("Event Triggered")
command = "/usr/bin/sudo /sbin/shutdown -r now"
import subprocess
process = subprocess.Popen(command.split(), stdout=subprocess.PIPE)
output = process.communicate()[0]
print(output)
x=1
GPIO.add_event_callback(4,my_callback)
print("End")
My terminal code is
sudo python test1.py
My output is
Starting
End
When I enter the above python code into Python shell, I get the above output and upon triggering GPIO4, it shuts down.
When I call it from the Terminal I get the above outputs but upon triggering GPIO4 nothing happens.
What am I missing so this will work from the terminal screen?
Your script seems to exit directly without waiting for an event. You may want to use a function that blocks the script until an event happens.
if GPIO.wait_for_edge(4,GPIO.RISING):
my_callback()
at the end of the program will block the thread until an edge is detected. You don't seem to need x
in the function so I just omitted it. There is also no need for GPIO.add_event_detect(4, GPIO.RISING)
and GPIO.add_event_callback(4,my_callback)
with this change