2015-12-08 123 views
2

在线无法找到教程。当按下按钮时,python脚本会自动在Raspberry Pi上运行

当我按下按钮时,我想要一些python脚本运行。我不想先在Raspberry Pi的终端上运行python脚本,然后等待按下按钮,就像提到一些教程一样。我也希望在按下按钮后运行整个脚本,而不是必须在整个脚本运行期间按下按钮。

基本上,我希望脚本运行时无需连接到Raspberry Pi或GUI的HDMI监视器或鼠标。只需按一下按钮。

此外,如果任何人有图表如何设置与GPIO和代码,这将是非常有用的按钮。

我该怎么做?我找不到任何东西,看起来很简单。

回答

2

您将始终需要一些程序来监视输入,无论是键盘,鼠标还是连接到GPIO的按钮。在键盘和鼠标的情况下,操作系统为你提供这个。所以从GPIO引脚触发程序,你需要多写一个这样的脚本:

import RPi.GPIO as GPIO 
import time 
import subprocess 

GPIO.setmode(GPIO.BCM) 

GPIO.setup(18, GPIO.IN, pull_up_down=GPIO.PUD_UP) 

while True: 
    input_state = GPIO.input(18) 
    if input_state == False: 
     subprocess.call(something) 
     # block until finished (depending on application) 

这里有一个按钮,电路(从this tutorial

button circuit

2

轮询更有效的方法是使用中断:

#!/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 

(从http://raspi.tv/2013/how-to-use-interrupts-with-python-on-the-raspberry-pi-and-rpi-gpio

相关问题