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

Raspberry Pi Python按下按钮并运行一些代码,python,raspberry-pi3,Python,Raspberry Pi3,我是一个完全不懂Raspberry Pi和Python的人,我正在尝试制作一个带有5个LED和一个按钮的简单交通灯模拟器。这是我的密码: 尽管如此: 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.LO

我是一个完全不懂Raspberry Pi和Python的人,我正在尝试制作一个带有5个LED和一个按钮的简单交通灯模拟器。这是我的密码:

尽管如此:

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编号和按钮编号是正确的,那么我需要修复什么呢

首先,您似乎有倒置的

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


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

首先,您似乎有倒置的

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


然后在上面的程序中,不读取pin值,阅读文件内容。

当按下按钮时,您是否得到正确的值?我认为问题在于您的代码只检查了一次按钮点击,然后在整个led打开和关闭过程中,您的代码不再寻找输入事件。当按下按钮时,您是否得到正确的值?我认为问题在于您的代码是错误的只需检查一次按钮点击,然后在整个led打开和关闭过程中,您的代码不再寻找输入事件。
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)