如何使用 Python 中的按钮对可切换变量进行编码
How do I code a toggle-able variable with a button in Python
我这里有这段代码。它所做的只是当我按下一个已连线的按钮时,它每 .3 秒打印一次 "Button Pressed"。我已经尝试了所有方法,但我终其一生都无法弄清楚如何制作它,所以这个按钮可以在 True 和 False 之间切换变量,或者 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)
完全像这样:
>>> x = True
>>> x
True
>>> x = not x
>>> x
False
>>> x = not x
>>> x
True
只要按下按钮,您就可以将您正在使用的任何东西设置为等于 not [variable]
的布尔变量 (inputValue
?)。我不太明白你在代码中做了什么,但这里有一些伪代码:
Boolean switch = False
if button is pressed:
switch = not switch
您想知道按钮的状态是否发生了变化。
您需要跟踪状态并在从 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)
我这里有这段代码。它所做的只是当我按下一个已连线的按钮时,它每 .3 秒打印一次 "Button Pressed"。我已经尝试了所有方法,但我终其一生都无法弄清楚如何制作它,所以这个按钮可以在 True 和 False 之间切换变量,或者 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)
完全像这样:
>>> x = True
>>> x
True
>>> x = not x
>>> x
False
>>> x = not x
>>> x
True
只要按下按钮,您就可以将您正在使用的任何东西设置为等于 not [variable]
的布尔变量 (inputValue
?)。我不太明白你在代码中做了什么,但这里有一些伪代码:
Boolean switch = False
if button is pressed:
switch = not switch
您想知道按钮的状态是否发生了变化。
您需要跟踪状态并在从 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)