I'm trying to control some neopixels connected to an arduino via python and am running into a problem. For the purposes of this demo, they light up when the arduino receives the "H" or "L" character via serial.
My original script was:
import serial
import time
ser = serial.Serial('/dev/ttyACM0', 9600)
#this is necessary because once it opens up the serial port arduino needs a second
time.sleep(3)
ser.write('H')
While it worked fine when I typed it into the python console, the lights turned off about 3 seconds in when I ran it as a script. After doing some digging, it looked like one work around was to just turn the last bit into a while loop so the serial connection did not close:
import serial
import time
ser = serial.Serial('/dev/ttyACM0', 9600)
#this is necessary because once it opens up the serial port arduino needs a second
time.sleep(1)
while True:
ser.write('H')
time.sleep(3)
This kept the light on, but created a new problem. If I want the lights to change according to user input I can do it once:
import serial
import time
ser = serial.Serial('/dev/ttyACM0', 9600)
#this is necessary because once it opens up the serial port arduino needs a second
time.sleep(1)
choice= raw_input("1 or 2?")
if choice == "1":
while True:
ser.write('H')
time.sleep(3)
elif choice == "2":
while True:
ser.write('L')
time.sleep(3)
But then the script is just stuck in the sub loop. How do I keep the subloop running (i.e. keep the light on) but also waiting to respond to a new user input?
thank you!