【问题标题】:serial.serialutil.SerialException: [Errno 16] could not open port: [Errno 16] device or resource busy: '/dev/ttyACM0'serial.serialutil.SerialException:[Errno 16] 无法打开端口:[Errno 16] 设备或​​资源繁忙:'/dev/ttyACM0'
【发布时间】:2018-10-25 15:25:50
【问题描述】:

我正在尝试使用 Pyserial python 库将 Arduino Uno 的串行输出打印到我的屏幕上。

这是我的 Arduino 代码。它只是生成随机数并将其打印到串行监视器:

void setup() {
Serial.begin(9600);

}

void loop() {
    long rand = random(10);
    Serial.print(rand);
}

我的 python 代码只是应该将值从串行打印到命令行,这里是代码:

#!/usr/bin/python

import serial

ser = serial.Serial("/dev/ttyACM0",9600)
while True:
    thing = ser.readline()
    print(thing)

当 Arduino 向串行监视器打印随机数时,我运行我的 python 脚本并得到错误:

Traceback (most recent call last):
  File "/home/archimedes/anaconda3/lib/python3.6/site-packages/serial/serialposix.py", line 265, in open
    self.fd = os.open(self.portstr, os.O_RDWR | os.O_NOCTTY | os.O_NONBLOCK)
OSError: [Errno 16] Device or resource busy: '/dev/ttyACM0'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "pythonSerialTest.py", line 6, in <module>
    ser = serial.Serial("/dev/ttyACM0",9600)
  File "/home/archimedes/anaconda3/lib/python3.6/site-packages/serial/serialutil.py", line 240, in __init__
    self.open()
  File "/home/archimedes/anaconda3/lib/python3.6/site-packages/serial/serialposix.py", line 268, in open
    raise SerialException(msg.errno, "could not open port {}: {}".format(self._port, msg))
serial.serialutil.SerialException: [Errno 16] could not open port /dev/ttyACM0: [Errno 16] Device or resource busy: '/dev/ttyACM0'

【问题讨论】:

  • 只是为了确保我正确理解这一点:您的 Arduino 通过串行转 USB 电缆连接到计算机,并且您的 Python 脚本正在计算机上运行,​​试图读取 Arduino 的内容正在写入串行端口?对吗?
  • 另外,看看这个类似的问题:stackoverflow.com/q/40951728/2615940。它不是完全重复的,但可能有一些有用的信息。
  • 嗨,是的,这是正确的。谢谢,我会看看那个链接。

标签: python linux python-3.x arduino pyserial


【解决方案1】:

你不能让两个程序使用同一个串口。

关闭 Arduino IDE 中的串口监视器。


PS:您也尝试在 Python 中读取行,但您不是从 Arduino 发送它们。

Serial.println(rand);将数字打印成行。

【讨论】:

  • 感谢您的建议,我尝试关闭 Arduino 的串行监视器,然后运行 ​​python 脚本。然而,这一次,什么都没有发生,光标只是位于命令行下方。我认为它正在等待 Arduino 停止将值打印到串行。我会尝试添加一个 Serial.end();到我的 Arduino 代码。
  • 我尝试使用 Serial.end() 但 python 脚本给出了同样的错误:'resource busy'
  • Serial.end() 只是禁用 Arduino 上的串行。它不允许多个程序访问单个串行端口。
  • 我将 Serial.print(rand); 更改为 Serial.println(rand); 仍然收到相同的错误“资源繁忙”,我暂时没有想法。
  • 好的,我取得了一点进展,我在我的 Arduino 代码中排除了 Serial.begin(9600); 行,以下程序运行没有问题:#!/usr/bin/python import serial ser = serial.Serial("/dev/ttyACM0",9600) print(ser.name) ser.close() 输出为 /dev/ttyACM0
【解决方案2】:

我得到了resource busy error,因为 Python 试图访问串行监视器,但是由于我使用以下命令将代码上传到 Arduino:sudo make upload monitor clean,我的 PC 正在从 Arduino 访问串行监视器,这阻止了Python 能够从 Arduino 访问串行监视器。现在我只需使用 sudo make upload clean 将代码上传到 Arduino 并排除命令 monitor 如果我打算使用 Python 访问串行监视器。

【讨论】:

    猜你喜欢
    • 2017-04-18
    • 2022-12-03
    • 2023-02-10
    • 2023-03-15
    • 2023-03-06
    • 2017-09-02
    • 1970-01-01
    • 2012-04-03
    • 1970-01-01
    相关资源
    最近更新 更多