0

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.

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.