1

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)

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Suggestion: Since while is not a function call you should drop the parentheses and write while True:.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.