按下按钮时LED才会保持打开状态?

时间:2016-05-04 19:19:12

标签: button raspberry-pi raspberry-pi2 led

我试图用按钮打开和点亮LED,但按下按钮时它只会保持打开状态。我该如何解决这个问题?

下面是我正在使用的代码:

# Import the required module. 
import RPi.GPIO as GPIO
# Set the mode of numbering the pins. 
GPIO.setmode(GPIO.BCM)
#GPIO pin 10 is the output. 
GPIO.setup(13, GPIO.OUT)
#GPIO pin 8 is the input. 
GPIO.setup(6, GPIO.IN)
#Initialise GPIO13 to low (False) so that the LED is off. 
GPIO.output(13, False)
while 1:
    if GPIO.input(6):
        GPIO.output( 13, True)
    else:
        GPIO.output( 13, False)
#keep LED on till the button pressed again then it turns off?

[编辑] 当我运行代码时,led开始关闭(正如我想要的那样)然后当按下按钮时,LED指示灯会亮起,但它只会在按钮处于打开状态时保持亮起状态压制住了。我希望它是一个按下打开LED,它将保持打开直到再次按下按钮。

3 个答案:

答案 0 :(得分:1)

试试这个:

isPressed = False
isOn = False
while 1:
    if GPIO.input(6):
        isPressed = True
    elif isPressed:
        isOn = not isOn
        GPIO.output( 13, isOn)
        isPressed = False

此按钮在释放按钮时切换(大多数操作系统上的默认按钮行为)。反过来说:

isPressed = False
isOn = False
while 1:
    if GPIO.input(6):
        if not isPressed:
            isPressed = True
            isOn = not isOn
            GPIO.output( 13, isOn)
    else:
        isPressed = False

答案 1 :(得分:0)

只要按下按钮,您的代码就会保持LED代码。

您可以通过将LED状态保存在变量中来实现切换机制

...
ledState = False
buttonPressed = False;

 ...

 if GPIO.input(6): 
     if not buttonPressed: 
        buttonPressed = True
        ledState = not ledState
        GPIO.output(13, ledState)
 else 
     buttonPressed = False

答案 2 :(得分:0)

如果您使用gpiozero作为led和按钮,

这是我写的代码。不是最好的代码,但能够帮助你。

def onLight():
garageLed = LED(21)  # Yellow LED lights up when the user is authorised
button = Button(13, pull_up=False)
reading = True;
while reading:
    if (garageLed.is_lit == False): 
        button.wait_for_press()  
        button.when_pressed = ledON() 
        button.wait_for_release()
        button.when_released = ledON()
    elif (garageLed.is_lit == True): 
        button.wait_for_press()
        button.when_pressed = ledOFF()
        button.wait_for_release()
        button.when_released = ledOFF()