2

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!

mweinberg
  • 161
  • 11
  • These might help: http://stackoverflow.com/questions/32369495/how-to-wait-for-an-input-without-blocking-timer-in-python , http://stackoverflow.com/questions/16828387/how-to-accept-user-input-without-waiting-in-python , http://stackoverflow.com/questions/31340/how-do-threads-work-in-python-and-what-are-common-python-threading-specific-pit – Ted Klein Bergman Jul 17 '16 at 15:34

1 Answers1

2

This is the solution I found myself.

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?")
Jongware
  • 22,200
  • 8
  • 54
  • 100
mweinberg
  • 161
  • 11