在 GPIO 输入的上升沿关闭终端

Shutdown with terminal on rising edge of GPIO input

我试图触发我的 Raspberry Pi 在 GPIO #4 的上升沿关闭。我最终想在启动时自动 运行 这个脚本。

我的 python 代码在文件 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")

我的终端代码是

sudo python test1.py

我的输出是

Starting
End

当我将上面的 python 代码输入 Python shell 时,我得到上面的输出并且在触发 GPIO4 时,它关闭了。

当我从终端调用它时,我得到了上面的输出,但是在触发 GPIO4 时没有任何反应。

我错过了什么所以这可以在终端屏幕上运行?

您的脚本似乎没有等待事件就直接退出了。您可能希望使用一个函数来阻止脚本直到事件发生。

if GPIO.wait_for_edge(4,GPIO.RISING):
    my_callback()

在程序结束时将阻塞线程,直到检测到边缘。您似乎不需要 x 在函数中,所以我只是省略了它。此更改

也不需要 GPIO.add_event_detect(4, GPIO.RISING)GPIO.add_event_callback(4,my_callback)