用户输入时中断循环(通过arduino和python 2.7控制Neopix)
我试图控制一些通过python连接到arduino的Neopix,但遇到了一个问题。在本演示中,当arduino通过串口接收到“H”或“L”字符时,它们亮起 我最初的剧本是:用户输入时中断循环(通过arduino和python 2.7控制Neopix),python,python-2.7,arduino,pyserial,Python,Python 2.7,Arduino,Pyserial,我试图控制一些通过python连接到arduino的Neopix,但遇到了一个问题。在本演示中,当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
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)
但是脚本只是停留在子循环中。如何保持子循环运行(即保持灯亮),同时等待响应新的用户输入
谢谢大家! 这就是我自己找到的解决方案
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?")
这些可能会有帮助:,