简体   繁体   中英

How to stop a while loop with a user input without interrupting the program?

How do I infinitely loop 5 led lights to keep turning on one after the other until the user inputs something? I don't want the user input to interrupt the loop. Right now everything works well except that in the middle of the loop the input interrupts the program.

import time
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)

print("Press h to exit the program")

while True:

    GPIO.setup(19,GPIO.OUT)
    GPIO.output(19,True)
    time.sleep(0.5)
    GPIO.output(19,False)

    GPIO.setup(26,GPIO.OUT)
    GPIO.output(26,True)
    time.sleep(0.5)
    GPIO.output(26,False)

    GPIO.setup(22,GPIO.OUT)
    GPIO.output(22,True)
    time.sleep(0.5)
    GPIO.output(22,False)

    GPIO.setup(27,GPIO.OUT)
    GPIO.output(27,True)
    time.sleep(0.5)
    GPIO.output(27,False)

    GPIO.setup(17,GPIO.OUT)
    GPIO.output(17,True)
    time.sleep(0.5)
    GPIO.output(17,False)

    x = input("")

    if (x == "h"):
        print("Exiting the program")
        break

    GPIO.setwarnings(False)

GPIO.cleanup()

You can use the third-party keyboard library to do this quite easily.

import keyboard

while True:
    print(1)
    print(2)
    print(3)
    print(4)
    if keyboard.is_pressed("h"):
       break

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM