mweinberg mweinberg - 3 months ago 15
Python Question

Interrupt while loop with user input (controlling neopixels via arduino and python 2.7)

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!

Answer

As instructed, I've removed solved and added the solution I used below.

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(2)

#ask for the initial choice
choice= raw_input("1 or 2?")

#keeps the loop running forever
while True:

    #if the initial choice is 1, do this
    while choice == "1":

        #send the H signal to the arduino
        ser.write('H')

        #give the user a chance to modify the chioce variable
        #if the variable is changed to 2, the while condition will no longer
        #be true and this loop will end, giving it an oppotunity to go
        #do the second while condition.
        #pending the decision the light will stay on
        choice= raw_input("1 or 2?")


    while choice == "2":

        ser.write('L')

        choice= raw_input("1 or 2?")