2016-09-12 99 views
1

我有一個Python腳本,將字符串test寫入Arduino串行端口。如果Arduino的接收test串,應該用字符串ok回覆和LED 13謹向上..Python的串行寫入Arduino是不同於Arduino的串行監視器的串行寫入

問題:當Arduino的串行監視器用於寫入test到串行端口,Arduino的回覆與ok如預期並且LED#13點亮。

但是,當Python腳本將test寫入同一個串行端口時,什麼都不會發生。 Arduino不響應串口,LED#13不亮。

任何想法如何修復Python腳本以獲得來自Arduino和LED 13的ok響應點亮?

Arduino的素描

int ledPin = 13; 


void setup() { 
    Serial.begin(9600); 
    pinMode(ledPin, OUTPUT); 
} 


void loop() { 

    while(Serial.available() == 0) { } 

    if(Serial.readString() == "test\r\n") { 
     Serial.print("ok\r\n"); 
     digitalWrite(ledPin, HIGH); 
    } 

    readString = ""; // Clear recieved buffer 
    delay(100); 
} 

的Python腳本

port = 'COM5' 
ser = serial.Serial(
    port=port, 
    baudrate=9600, 
    timeout=5 
) 

serial.write("test\r\n") 

response = serial.readline() 
print response 

回答

2
port = 'COM5' 
ser = serial.Serial(
    port=port, 
    baudrate=9600, 
    timeout=5 
) 

# you need to sleep after opening the port for a few seconds 
time.sleep(5) # arduino takes a few seconds to be ready ... 

#also you should write to your instance 
ser.write("test\r\n") 
# and give arduino time to respond 
time.sleep(0.5) 
response = self.serial.readline() 
print response 

,如果你不想等待,你可能需要等待ser.cts秒固定數量(清除發送)

+1

作品!花了一個多小時試圖編碼字符串和東西lol – Nyxynyx

+0

我已經有了python + serial + ardiuno的經驗lottttts; P –

+0

太棒了!一個相關的問題:在Python中的無限循環中,發送'test'後,Arduino需要大約一秒的時間回覆'ok'。有沒有辦法加快這一點? – Nyxynyx