8

我正在尝试用 Python 编写一个程序,该程序将循环以继续检查串行端口(COM4)并在从串行端口读取字符“1”时打印出一条消息。我想通过按一下按钮从 Arduino 小工具的串行端口发送“1”。

但是,当我尝试创建串行对象的实例时,出现错误“[错误 5]:访问被拒绝”。(它会在实例化时自动尝试打开,这是错误所在,从我从处理此问题的 PySerial 包中的文件中可以看到。)

我的代码:

c = serial.Serial('COM4', 9600)
while True:
    signal = c.read()
    print signal
    print "running"
    time.sleep(2)
    c.flushOutput()

但是,它永远不会超过“c = serial.Serial('COM4', 9600)。这就是错误弹出的地方。我该如何解决这个问题?

4

7 回答 7

5

对我来说,解决方案不起作用,但起作用的是关闭所有与给定 com 端口交互的应用程序。

于 2017-02-11T19:24:37.607 回答
3

更新:这显然在 PySerial 3.0 中不再可能。

在 Windows 下,我总是成功地使用了 port=<int> 方法。

即将您的代码更改为:

c = serial.Serial(3, 9600)
于 2011-11-28T03:22:04.927 回答
2

请注意python版本。

从 pyserial 手册中关于:class serial.Serial https://pyserial.readthedocs.io/en/latest/pyserial_api.html#classes

............

当给定端口时,该端口在对象创建时立即打开。当端口为 None 并且需要连续调用 open() 时,它不会打开。

port 是设备名称:取决于操作系统。例如 GNU/Linux 上的 /dev/ttyUSB0 或 Windows 上的 COM3。

…………

在 3.0 版更改: 不再支持数字作为端口参数

于 2016-08-27T13:00:49.963 回答
1

用于Python 2.6使用从零开始的 COM 端口索引。因为Python 2.7.x您可以使用全名“COM4”。根据我的经验,最好使用 2.7 版本。安装Python 2.7.x安装工具(又名 Easy Install)。一旦你有了这个,通过键入来安装 pyserial 模块easy_install -U pyserial(参见pyserial 安装文档)。

请记住将 python 路径添加到PATH环境变量。

于 2013-03-09T15:39:44.373 回答
1

在 python 中与 PORT COM N-1 一起使用(N 是你的 COM 数)

于 2015-02-08T18:42:23.850 回答
0

关闭从 Arduino IDE 打开的串行监视器。

于 2021-09-03T11:05:18.330 回答
0
    At one time, there is only an application that can access one com port. If application A is accessing this com port, application B can not access it. You should do these following steps as below:
    1. Find the application that is accessing this port and then close the connection.
    2. Reconnect your application to this port. You can use the below source code.
    
     port='COM8',
 baudrate = 2400,
 parity=serial.PARITY_EVEN,
 stopbits=serial.STOPBITS_ONE,
 bytesize=serial.SEVENBITS,
 timeout=None
)

while 1:
 x = ser.readline()
 print(x)
于 2021-12-24T02:17:19.967 回答