用户输入中断while循环(通过arduino和python 2.7控制neopixels)

时间:2016-07-17 15:12:07

标签: python python-2.7 arduino pyserial

我正试图控制一些通过python连接到arduino的neopixels并遇到问题。出于本演示的目的,当arduino通过串行接收“H”或“L”字符时,它们会亮起。

我的原始剧本是:

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')

当我将它输入python控制台时工作正常,当我将其作为脚本运行时,灯会关闭约3秒钟。在进行了一些挖掘之后,看起来一个解决方法是将最后一位转换为while循环,以便串行连接没有关闭:

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)

这保持了亮点,但却产生了一个新问题。如果我想根据用户输入改变灯光,我可以做一次:

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)

但是后来脚本停留在子循环中。如何保持子循环运行(即保持灯亮),还等待响应新的用户输入?

谢谢你!

1 个答案:

答案 0 :(得分:2)

这是我发现自己的解决方案。

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?")