【问题标题】:Serial communication error between Arduino and PythonArduino和Python之间的串行通信错误
【发布时间】:2018-08-08 14:29:14
【问题描述】:

我想将值从 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。

如果这是一个简单的错误,我很抱歉,但我对串行和 Arduino 非常陌生。

【问题讨论】:

标签: python python-3.x arduino raspberry-pi serial-port


【解决方案1】:

您一次只能从一个应用程序连接到您的 Arduino 串行端口。 当你通过 Serial port Monitor 连接到它时,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()
    

【讨论】:

  • 我现在可以正常工作了,谢谢!现在是否可以通过蓝牙(RPi 和智能手机)与 RPi 进行通信,或者使用 Arduino / RPi 通信已经使用的串行端口?
  • 我的回答对你有帮助吗,还是你自己弄清楚了如何处理这个问题?如果您将蓝牙加密狗连接到您的 RPi,它将不会使用您的串行端口。如果你的树莓派内置了蓝牙芯片,那么串口应该没有问题。是arduino,它限制了串口,而不是RPI,它更像PC而不是微控制器平台。
  • 起初我尝试了您的代码,但不知何故仍然无法正常工作,然后我找到了本指南:forum.arduino.cc/index.php?topic=396450,它完全按照我的意愿工作:) 我很高兴蓝牙将是可能的,现在我只需要弄清楚如何。
  • 好的,当您尝试使用该技术做某事时,最好先阅读文档 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-08-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-09
相关资源
最近更新 更多