Amar Shah
Amar Shah

Reputation: 87

Python serial empty data

I am having a script, which is reading data from a device sending data from 1 to 9 via RS232 cable. I am taking the data with below script.

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)

The output is as below

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

I am not able to understand, why the first data is coming as empty, and how can I fix it. Its necessary, since I am collecting this data and would be entering into Db.

Upvotes: 0

Views: 5770

Answers (1)

bdoubleu
bdoubleu

Reputation: 6107

It's because you're only receiving the end of line character and not waiting until you receive serial data.

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

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

You could ignore empty data.

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

Upvotes: 2

Related Questions