Skip to main content
 首页 » 编程设计

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

2024年10月17日37JustinYoung

我正在尝试通过 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) 

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

谢谢!

请您参考如下方法:

这是我自己找到的解决方案。

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