Search code examples
pythonpython-3.xraspberry-pikeyboardled

LED control using keyboard on Raspberry Pi 4 - Python


I am completely novice in Python and in Raspberry Pi. However, I have one, maybe easy to solve problem. I want to control LED diod on RPi4 with a keyboard. If I press "1", I want the LED be active, and if I press "0" or any other key, I want to LED be inactive. I am running Python 3.7.3 on my Raspberry Pi4. The code below is working, but when I press "1" or "0", I have to run my code via command line again if I want to change status of LED.

Is there any solution, how to still read an input from keyboard and automatically based on it change the status of the LED?

import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)
GPIO.setup(14,GPIO.OUT)

user_input = input("Input value 0 or 1: ")
print(user_input)

while (True):
    if user_input == "1":
        GPIO.output(14,GPIO.HIGH)
        time.sleep(1)
    else:
        GPIO.output(14,GPIO.LOW)
        time.sleep(1)

Solution

  • You are only asking for the user input once. move the input(...) within the while loop.

    import RPi.GPIO as GPIO
    import time
    
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(14,GPIO.OUT)
    
    while True:
        user_input = input("Input value 0 or 1: ")
        print(user_input)
    
        if user_input == "1":
            GPIO.output(14,GPIO.HIGH)
            time.sleep(1)
        else:
            GPIO.output(14,GPIO.LOW)
            time.sleep(1)