Hello. I'm a complete Python beginner and I'd like to know how to add a fail-safe to your code so that the script is stopped after a certain phrase or key combination has been given as input.
To explain further, I'm playing around with a Raspberry Pi at work. I created a simple circuit with a LED, button and a few lines of code to control it all. I start the python script which can only be stopped manually (CTRL+C or CTRL+Z) in the terminal. The script waits for a user input, which in this case, is pressing the button, and when that happens the LED lights up and the output in the terminal is "Button pressed". The script continues to run until I press CTRL+C which is a terminal bound command I belive.
I'd like to do the following: The script runs for an infinite amount of time, but if I input "stop" or "close" or something like that instead of pressing the button, it should stop immediately (just like with CTRL+C).
stop = raw_input("Phrase: ") if stop == "stop": sys.exit(0) else: MAIN
But that's not what I'm looking for because now the main script doesn't work like it's supposed to. I'd like the script to run as it did before I added the above lines, but when I input something from the keyboard instead of pressing the button it stops.
Just in case things are unclear here's the whole code:
import RPi.GPIO as GPIO import sys #set pin 8 as input, pin 10 as output GPIO.setmode(GPIO.BOARD) GPIO.setup(8, GPIO.IN) GPIO.setup(10, GPIO.OUT) #reset pins if CTRL+C or CTRL+Z is pressed try: while True: #save value from pin 8 input_value = GPIO.input(8) var = raw_input("Phrase: ") if var == "stop": sys.exit(0) else: #if value on pin 8 is false (button pressed) if input_value == False: #light up the LED GPIO.output(10, GPIO.HIGH) print("Button pressed") #check value on pin 8 again while input_value == False: input_value = GPIO.input(8) else: #else LED is off GPIO.output(10, GPIO.LOW) except KeyboardInterrupt: GPIO.cleanup()
Note: The code isn't mine completely. Most of it is copied from people who posted tutorials for controlling a LED with a switch through a Raspberry Pi.