Python - Read From The Serial Port Data Line By Line Into A List When Available
I am aiming to write a code that will be indefinitely listening and reading from to a serial port that will have this output produced every few seconds serial port output: aaaa::ab
Solution 1:
readline
will keep reading data until read a terminator(new line). please try: read
.
UPDATED:
use picocom -b 115200 /dev/ttyUSB0
or putty(serial model) to detect the port and baud-rate is right. I got two different ports in your two questions.if open error port, read()
will keep waiting until read a byte. like this:
import serial
# windows 7
ser = serial.Serial()
ser.port = 'COM1'
ser.open()
ser.read() # COM1 has no data, read keep waiting until read one byte.
if you type this code in console, console will no output like this:
>>> import serial
>>> ser = serial.Serial()
>>> ser.port = 'COM1'
>>> ser.open()
>>> ser.read()
_
we need add timeout for read to fix it.
you can try this:
import serial
import time
z1baudrate = 115200
z1port = '/dev/ttyUSB0' # set the correct port before run it
z1serial = serial.Serial(port=z1port, baudrate=z1baudrate)
z1serial.timeout = 2 # set read timeout
# print z1serial # debug serial.
print z1serial.is_open # True for opened
if z1serial.is_open:
while True:
size = z1serial.inWaiting()
if size:
data = z1serial.read(size)
print data
else:
print 'no data'
time.sleep(1)
else:
print 'z1serial not open'
# z1serial.close() # close z1serial if z1serial is open.
Post a Comment for "Python - Read From The Serial Port Data Line By Line Into A List When Available"