串口通讯readline数据获取不到正确数据。 readline 数据是之前返回的写入数据,但有时可以获得不同的数据。
这是代码
import time
import serial
ser = serial.Serial()
rereport = "COM16"
ser.baudrate = 9600
ser.bytesize = serial.EIGHTBITS #number of bits per bytes
ser.parity = serial.PARITY_NONE #set parity check: no parity
ser.stopbits = serial.STOPBITS_ONE #number of stop bits
ser.timeout = 1
ser.xonxoff = True #disable software flow control
ser.rtscts = 0 #disable hardware (RTS/CTS) flow control
ser.dsrdtr = 0 #disable hardware (DSR/DTR) flow control
ser.open()
ser.flushInput() #flush input buffer, discarding all its contents
ser.flushOutput()#flush output buffer, aborting current output
ser.reset_input_buffer()
ser.reset_output_buffer()
wdata = "#001STA"
ser.write(wdata.encode())
time.sleep(1)
print("Start")
if ser.is_open:
myBytes = ser.readline()
if myBytes:
while 1:
ser.write(wdata.encode())
time.sleep(0.1)
myBytes = ser.readline().decode()
print(myBytes)
time.sleep(1)
else:
print("Can not connect")