【发布时间】:2019-02-05 02:41:49
【问题描述】:
我正在尝试创建一个程序来检测三个不同按钮的状态,这些按钮连接到 Raspberry Pi 上的 GPIO 引脚,一旦所有三个按钮都为高电平,就会采取行动。现在我的所有按钮都通过回调函数单独工作,但“main”函数中的if 语句似乎没有运行。
这是我第一次使用 Python,如果您在我的代码结构中发现任何其他逻辑错误,请告诉我。仍在尝试掌握它,尤其是 GPIO 库函数。在此先感谢,我已经在下面发布了我的代码。
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
butOne = False
butTwo = False
butThree = False
# Setup button inputs
GPIO.setup(19, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(20, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(21, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.add_event_detect(19, GPIO.RISING)
GPIO.add_event_detect(20, GPIO.RISING)
GPIO.add_event_detect(21, GPIO.RISING)
def butOne_callback(channel1):
print("Button 1 /n")
butOne = True
def butTwo_callback(channel2):
print("Button 2 /n")
butTwo = True
def butThree_callback(channel3):
print("Button 3 /n")
butThree = True
def main():
GPIO.add_event_callback(19, butOne_callback)
GPIO.add_event_callback(20, butTwo_callback)
GPIO.add_event_callback(21, butThree_callback)
if (butOne == True) and (butTwo == True) and (butThree == True):
print("All Depressed")
main()
更新的代码,根据 Aditya Shankar 的建议:
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(19, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(20, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(21, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.add_event_detect(19, GPIO.RISING)
GPIO.add_event_detect(20, GPIO.RISING)
GPIO.add_event_detect(21, GPIO.RISING)
def butOne_callback(channel1):
print("Button 1 /n")
butOne = True
check_all_depressed()
def butTwo_callback(channel2):
print("Button 2 /n")
butTwo = True
check_all_depressed()
def butThree_callback(channel3):
print("Button 3 /n")
butThree = True
check_all_depressed()
def check_all_depressed():
if butOne and butTwo and butThree:
print("All Depressed")
GPIO.add_event_callback(19, butOne_callback)
GPIO.add_event_callback(20, butTwo_callback)
GPIO.add_event_callback(21, butThree_callback)
运行代码并按下按钮时收到错误:
Traceback(最近一次调用最后一次): 文件“/home/pi/Downloads/GPIO_test_06.py”,第 21 行,在 butTwo_callback check_all_depressed() 文件“/home/pi/Downloads/GPIO_test_06.py”,第 29 行,在 check_all_depressed 如果 butOne 和 butTwo 和 butThree: NameError: name 'butOne' 未定义
【问题讨论】:
-
尝试将 if 语句包装在
while True循环中,看看会发生什么(将while True放在 if 语句上方,然后在其下方缩进 2 行)。 -
问题还出在其他函数上,不仅仅是
main()。见stackoverflow.com/questions/14421733/… -
每个写入全局变量的函数都需要一个全局语句,列出它写入的全局变量的名称。
标签: python raspberry-pi gpio