如何在Python中用按钮编写可切换变量

2024-04-25 00:21:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我这里有密码。它所做的就是当我按下一个连接好的按钮时,它每3秒打印一次“button Pressed”。我什么都试过了,但我一辈子都不知道怎么做,所以这个按钮在真和假之间切换变量,或者0,1,等等。。。我真的很感激你的帮助。谢谢

 import  RPi.GPIO as GPIO
import time


GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.IN,pull_up_down=GPIO.PUD_UP)


while True:
    inputValue = GPIO.input(18)
    if (inputValue == False):
        print("Button press ")
    time.sleep(0.3)

完全像这样:

https://www.youtube.com/watch?v=PH3hNLXxNeE


Tags: inimport密码gpiotimeassetupbutton
2条回答

你想知道按钮的状态是否改变了。在

您需要跟踪状态,并在从GPIO获取新值时进行比较。在

latest_state = None

while True:
    inputValue = GPIO.input(18)
    if inputValue != latest_state:
        latest_state = inputValue
        if latest_state:
            print("Button pressed")
        else:
            print("Button depressed")
    time.sleep(0.3)
>>> x = True
>>> x
True

>>> x = not x
>>> x
False

>>> x = not x
>>> x
True

无论何时按下按钮,您都可以设置作为布尔变量(inputValue?)等于not [variable]。我不太明白您在代码中做了什么,但这里有一些伪代码:

^{pr2}$

相关问题 更多 >