Reputation: 833
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::abcd:0:0:0
//printf("%d\n",data[0]);
2387
//printf("%d\n",data[1]);
14
-9
244
-44
108
I want the data to be appended in a list like this, python supposed output
[abcd::abcd:0:0:0, 2387, 14, -9, 244, -44, 108]
I tried this code amongst many others but nothing worked, I keep on getting no output EDIT- the code below gives me this output
'''[['abcd::', 'abcd::', 'abcd::', 'abcd::', 'abcd::']] #or
[['abcd::abcd:0:0:c9\n', '2406\n', '14\n', '-7\n']] # and so on, different output for each iteration'''
#[['aaaa::c30c:0:0:c9\n', '2462\n', '11\n', '-9\n', '242\n', '-45\n', '106\n']] apparently it worked only once.
ser = serial.Serial('/dev/ttyUSB1',115200, timeout=10)
print ser.name
while True:
data = []
data.append(ser.readlines())
print data
# further processing
# send the data somewhere else etc
print data
ser.close()
Upvotes: 2
Views: 42120
Reputation: 137
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.
Upvotes: 3