0

I am reading from the serial port using the following code:

z1baudrate = 115200
z1port = '/dev/ttyUSB11'
ser = serial.Serial(z1port, z1baudrate, timeout=0, parity=serial.PARITY_NONE,

                    stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS)
while True:
    queue = ser.inWaiting()
    if queue > 0:
        data = ser.read(1000)
        print data
    time.sleep(.2)

I am supposed to get this result printed every few seconds

bbbb::0000:0:0:00 2412 7 -1 250 -58 108 0 2398 # output 1 
bbbb::0000:0:0:00 2475 4 1 264 -46 106 1 2423 # output 2

but instead, I occasionally receive incomplete output like

bbbb::0000:0:0:00 # sometimes broken into 2 lines
2412 7 -1 250 -58 108 0 2398 # line 2
bbbb::0000 # sometimes a part of the output is missing like this 
bbbb::0000:0:0:00 2475 4 # or like this. Length is variable!

What is the problem? Is it a synchronization issue? How do I fix this?

1 Answer 1

1

It is a combination of the sleep and print statement. The program might sleep while a sentence is being received, and the when the print command is used, it will write a new line, each time.

Try this:

import sys

z1baudrate = 115200
z1port = '/dev/ttyUSB11'
ser = serial.Serial(z1port, z1baudrate, timeout=0, parity=serial.PARITY_NONE,

                    stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS)
while True:
    data = ser.readline()
    sys.stdout.write(data)
Sign up to request clarification or add additional context in comments.

7 Comments

I would also try to avoid using the sleep in a loop like this. You should maybe look into the readline from pyserial for this.
How about removing the sleep, will it work? I am currently testing your answer
And if I use readline, then how much should I set the timeout?
I am testing the readline now because the sys.stdout didn't workout. I however got a few times more than one line together like this as the output bbbb::0000:0:0:00 2412 7 -1 250 -58 108 0 2398 bbbb::0000:0:0:00 2475 4 1 264 -46 106 1 2423# I have two lines together as the output!This may be due to the fact that I receive the output at random times sometimes, but how to eliminate this?
Did you remember to import sys when using sys.stdout.write?
|

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.