首页 > 解决方案 > 在 main() 函数内部使用 Python 中的 IF 语句

问题描述

我正在尝试创建一个程序来检测三个不同按钮的状态,这些按钮连接到 Raspberry Pi 上的 GPIO 引脚,一旦所有三个按钮都为高电平,就会采取行动。现在我的所有按钮都通过回调函数单独工作,但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)

运行代码并按下按钮时收到错误:

回溯(最近一次调用):文件“/home/pi/Downloads/GPIO_test_06.py”,第 21 行,在 butTwo_callback check_all_depressed() 文件“/home/pi/Downloads/GPIO_test_06.py”,第 29 行,在 check_all_depressed if butOne and butTwo and butThree: NameError: name 'butOne' is not defined

标签: pythonraspberry-pigpio

解决方案


您的if语句运行,但只运行一次 - 在脚本首次启动时立即运行。到那时,按钮还没有被按下,因此它似乎不起作用。

解决该问题的一种方法是将语句放入一个具有小延迟的循环中,并测试该循环中的条件。就像是:

import time

while not condition:
    time.sleep(1)

另一个问题是风格问题。你可以写下你的条件:

(butOne == True) and (butTwo == True) and (butThree == True)

就像:

butOne and butTwo and butThree

因为它们都是布尔值。在 Python 中,您甚至可以编写:

all([butOne, butTwo, butThree])

这不是更短,但如果你有更多的条件,它会避免and一次又一次地重复。

最后,您选择创建一个运行主程序的主函数。将函数定义上方的所有代码也包含在其中可能是个好主意。毕竟,它都是你的主程序的一部分,而且都意味着只运行一次。这样,您还可以避免在函数内部意外使用全局变量,这可能会导致意外(但技术上正确)的行为。


推荐阅读