Python串口空数据

Python serial empty data

我有一个脚本,它正在从通过 RS232 电缆从 1 发送数据到 9 的设备中读取数据。我正在使用以下脚本获取数据。

import serial

ser = serial.Serial(
    port='COM3', \
    baudrate=9600, \
    parity=serial.PARITY_NONE, \
    stopbits=serial.STOPBITS_ONE, \
    bytesize=serial.EIGHTBITS, \
    timeout=10)

while True:
    data_raw = ser.readline().decode().strip()
    print("Data is: " + data_raw)

输出结果如下

Data is: 
Data is: 5
Data is: 6
Data is: 7
Data is: 8
Data is: 9
Data is: 1

我无法理解,为什么第一个数据是空的,我该如何解决。 这是必要的,因为我正在收集这些数据并将进入 Db。

这是因为您只接收到行尾字符,而没有等到接收串行数据。

print('Data is: ' + b'\n'.decode().strip())
print('Data is: ' + b'5\n'.decode().strip())

>>> Data is: 
>>> Data is: 5

您可以忽略空数据。

while True:
    data_raw = ser.readline().decode().strip()
    if data_raw:
        print("Data is: " + data_raw)