pySerial 可以写,但不能读 [英] pySerial can write, but not read

查看:97
本文介绍了pySerial 可以写,但不能读的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 Windows 10 机器(Python 3.6.4,32 位)上使用 pySerial 从一台通常会将其数据记录到串行 ASCII 打印机的实验室设备读取串行数据.使用 USB 转串口适配器进行连接.

I am trying to use pySerial on a Windows 10 machine (Python 3.6.4, 32 bit) to read serial data from a piece of lab equipment that would normally log its data to a serial ASCII printer. Connecting using a USB-to-serial adaptor.

如果我将计算机连接到打印机,我可以使用 serial.write() 进行打印,所以我知道我的适配器正在工作.但是,当我将计算机连接到实验室设备并尝试使用以下代码读取数据时,却一无所获:

If I connect the computer to the printer, I can print using serial.write(), so I know my adaptor is working. However, when I connect the computer to the lab equipment and try to read data using the following code, I get nothing all:

import serial
ser = serial.Serial('COM5')
while True:
    if ser.in_waiting != 0:
        datastring = ser.read(size=ser.in_waiting)
        print(str(datastring))

当我运行代码时,我知道实验室设备正在传输.还尝试将两个 USB 转串行适配器连接到计算机,并在适配器之间使用串行电缆并将数据从一个串行端口发送到另一个.再次,我可以毫无问题地写入,但另一个端口什么也没有收到.

I know the lab equipment is transmitting when I run the code. Have also tried connecting two USB-to-serial adaptors to the computer with a serial cable in-between the adaptors and sending data from one serial port to the other. Again, I can write without problem, but the other port receives nothing.

我发现硬件有问题.我已使用标准串行电缆将实验室设备连接到我的 USB 转串口适配器(出于测试目的,两个 USB 转串口适配器相互连接).使用空调制解调器连接解决了问题.

I turned out to have a hardware problem. I had connected the lab equipment to my USB-to-serial adaptor (and, for testing purposes, the two USB-to serial adaptors to each other) using a standard serial cable. Connecting using a null modem solved the problem.

推荐答案

您可能遇到波特率问题,您应该声明如下内容:

you may have a problem of baud rate you should declare something that look like :

import serial
ser = serial.Serial('COM5', 9600, timeout=None) #<- 9600 is the baud rate

while True:
    data = ser.readline()
    print(data)

编辑

While True:
    bytesToRead = ser.inWaiting()
    data=ser.read(bytesToRead)
    print(data)

这篇关于pySerial 可以写,但不能读的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆