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

LED will only stay turned on when the button is pushed down?

我试图用一个按钮打开 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,它会一直亮着直到再次按下按钮。

只要按下按钮,您的代码就会使 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

试试这个:

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

这会触发释放按钮(大多数 OS 上的默认按钮行为)。反过来:

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

如果您将 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()