问题
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.
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))
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.
EDIT: 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.
回答1:
There are many causes to this kind of problem, the first things that comes to my mind is that you have a low timeout
for your serial, and you close the connection before anything can be received:
ser = serial.Serial('COM5', timeout=None)
other values that you may check are the following:
ser = serial.Serial('COM5', baudrate=9600, bytesize=8, parity='N', stopbits=1, timeout=None, xonxoff=False, rtscts=False)
回答2:
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)
EDIT
While True:
bytesToRead = ser.inWaiting()
data=ser.read(bytesToRead)
print(data)
来源:https://stackoverflow.com/questions/49408849/pyserial-can-write-but-not-read