簡體   English   中英

Arduino和Python之間的串行通信錯誤

[英]Serial communication error between Arduino and Python

我想將Raspberry Pi上的Python程序中的值發送到Arduino。 我的RPi程序如下所示:

import time, serial
time.sleep(3)
ser = serial.Serial('/dev/ttyACM0', 9600)
ser.write(b'5')

我的Arduino程序:

void setup() {
    Serial.begin(9600);                    // set the baud rate
    Serial.println("Ready");               // initial "ready" signal
}

void loop() {
    char inByte = ' ';
    if(Serial.available()) {         
        inByte = Serial.read();
        Serial.println(inByte);
    } 
    delay(100)
}

我的問題是,當我使用Python運行該程序並隨后在Arduino IDE中打開串行監視器時,它僅顯示“就緒”,而不顯示發送的值。 如果我想在程序同時打開監視器,則出現錯誤:

設備或資源繁忙:'/ dev / ttyACM0'

我正在使用Python 3.6。

如果這是一個簡單的錯誤,我感到很抱歉,但是我對Serial和Arduino很陌生。

您一次只能通過一個應用程序連接到Arduino串行端口。 通過串行端口監視器連接到它時,Python無法連接到它。

您有兩種解決方案:

  1. 使用串行嗅探器代替Arduino IDE的串行監視器。 關於此主題還有另一個已回答的問題: https : //unix.stackexchange.com/questions/12359/how-can-i-monitor-serial-port-traffic

  2. 不要使用任何串行監視器,使用Python! 您可以連續從序列中讀取內容,並打印收到的內容,如下所示:

     import time, serial time.sleep(3) ser = serial.Serial('/dev/ttyACM0', 9600) # Write your data: ser.write(b'5') # Infinite loop to read data back: while True: try: # get the amount of bytes available at the input queue bytesToRead = ser.inWaiting() if bytesToRead: # read the bytes and print it out: line = ser.read(bytesToRead) print("Output: " + line.strip()) except IOError: raise IOError() 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM