Raspberry Pi Python按下按钮并运行一些代码

时间:2016-06-24 17:55:09

标签: python raspberry-pi3

我是Raspberry Pi和Python的总菜鸟,我试图制作一个带有5个LED和一个按钮的简单交通灯模拟器。这是我的代码:

而True:

inputValue = GPIO.input(17)
if (inputValue == False): #if the button was pushed
    print("Button press ")
else: #if it wasn't pressed 
    GPIO.output(green_traf_LED, GPIO.LOW) #green T. LED on
    GPIO.output(red_walk_LED, GPIO.LOW) #red W. LED always on
    time.sleep(6)
    GPIO.output(green_traf_LED, GPIO.HIGH) #green T. LED off
    #yellow blinking, red
    for k in range(10):
        #red walk LED still on
        GPIO.output(yellow_traf_LED, GPIO.LOW) #yellow T. LED on
        time.sleep(0.2)
        GPIO.output(yellow_traf_LED, GPIO.HIGH) #yellow T. LED off
        time.sleep(0.2)
    #red, white
    GPIO.output(red_traf_LED, GPIO.LOW) #red T. LED ON
    time.sleep(6)
    GPIO.output(red_traf_LED, GPIO.HIGH) #red T. LED off
time.sleep(0.3)

所以基本上,当没有按下按钮时,我希望我的python代码运行代码x。当按下按钮时,我希望它运行代码y然后继续运行代码x直到我再次按下它。但是当我运行代码时,没有任何LED亮起,当我按下按钮时,消息不会出现。我100%确定接线,LED编号和按键编号是否正确,那么我需要修理什么?

1 个答案:

答案 0 :(得分:0)

首先,您似乎已经倒置了HIGHLOW

例如,您需要服务/后台脚本来侦听输入端口并将状态放在文件中。如果已安装,Node-RED可以监控GPIO端口,因此您无需对服务进行编程。

Source

import time
#initialise a previous input variable to 0 (assume button not pressed last)
prev_input = 0
while True:
    #take a reading
    input = GPIO.input(17)
    #if the last reading was low and this one high, print
    if ((not prev_input) and input):
        print("Button pressed") #put information in file or other...
        #update previous input
        prev_input = input
        #slight pause to debounce
        time.sleep(0.05)

然后在上面的程序中,而不是读取引脚值,读取文件内容。