2015-12-08 143 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

相關問題