网上找不到教程。
当我按下按钮时,我想要运行一些 python 脚本。我不想先在 Raspberry Pi 的终端上运行 python 脚本,然后像一些教程提到的那样等待按下按钮。我还希望整个脚本在按下按钮后运行,而不是我必须在脚本运行的整个持续时间内按下按钮。
基本上,我希望脚本无需连接到 Raspberry Pi 或 GUI 设备的 HDMI 显示器或鼠标即可运行。只需按一下按钮即可。
另外,如果有人有关于如何使用 GPIO 设置按钮和代码的图表,那将会非常有帮助。
我该怎么做呢??我在上面找不到任何东西,而且看起来很简单。
轮询的更有效替代方法是使用中断:
#!/usr/bin/env python2.7
# script by Alex Eames http://RasPi.tv/
# http://raspi.tv/2013/how-to-use-interrupts-with-python-on-the-raspberry-pi-and-rpi-gpio
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
# GPIO 23 set up as input. It is pulled up to stop false signals
GPIO.setup(23, GPIO.IN, pull_up_down=GPIO.PUD_UP)
print "Make sure you have a button connected so that when pressed"
print "it will connect GPIO port 23 (pin 16) to GND (pin 6)\n"
raw_input("Press Enter when ready\n>")
print "Waiting for falling edge on port 23"
# now the program will do nothing until the signal on port 23
# starts to fall towards zero. This is why we used the pullup
# to keep the signal high and prevent a false interrupt
print "During this waiting time, your computer is not"
print "wasting resources by polling for a button press.\n"
print "Press your button when ready to initiate a falling edge interrupt."
try:
GPIO.wait_for_edge(23, GPIO.FALLING)
print "\nFalling edge detected. Now your program can continue with"
print "whatever was waiting for a button press."
except KeyboardInterrupt:
GPIO.cleanup() # clean up GPIO on CTRL+C exit
GPIO.cleanup() # clean up GPIO on normal exit
(from http://raspi.tv/2013/how-to-use-interrupts-with-python-on-the-raspberry-pi-and-rpi-gpio http://raspi.tv/2013/how-to-use-interrupts-with-python-on-the-raspberry-pi-and-rpi-gpio)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)