2016-07-17 3 views
2

私はPython経由でarduinoに接続されているいくつかのネオピクセルを制御しようとしています。このデモの目的のために、arduinoがシリアル経由で "H"または "L"文字を受け取ったときに点灯します。ユーザー入力(アルドゥイノとPython 2.7経由でネオピクセルを制御する)中断中whileループ

私の元のスクリプトがいた:私はPythonのコンソールにそれを入力すると、それがうまく働いている間

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

、ライトは私がスクリプトとして、それを実行したときに約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) 

while True: 
    ser.write('H') 
    time.sleep(3) 

これは上の光を保ったが、新しい問題を作成しました:いくつかの掘削を行った後、それは周りのシリアル接続が閉じなかったので、ちょうどwhileループの中に最後のビットをオンにした1つの作業のように見えました。

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) 

をしかし、その後、スクリプトがちょうどサブループに陥っている:私はライトは、ユーザの入力に応じて変更したい場合は、私は一度それを行うことができます。サブループを稼働させたままにする(つまり、ライトをオンにする)だけでなく、新しいユーザー入力に応答するのを待っていますか?

ありがとうございました!

+0

これらのに役立つかもしれない: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-in-python、http://stackoverflow.com/questions/31340/how-do-threads-work-in-python-and-共通点 - python-threading-specific-pit –

答えて

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?") 
関連する問題