I have an Arduino connected to my computer running a loop, sending a value over the serial port back to the computer every 100 ms.
I want to make a Python script that will read from the serial port only every few seconds, so I want it to just see the last thing sent from the Arduino.
How do you do this in Pyserial?
Here's the code I tried which does't work. It reads the lines sequentially.
import serial
import time
ser = serial.Serial('com4',9600,timeout=1)
while 1:
time.sleep(10)
print ser.readline() #How do I get the most recent line sent from the device?
Best Answer
Perhaps I'm misunderstanding your question, but as it's a serial line, you'll have to read everything sent from the Arduino sequentially - it'll be buffered up in the Arduino until you read it.
If you want to have a status display which shows the latest thing sent - use a thread which incorporates the code in your question (minus the sleep), and keep the last complete line read as the latest line from the Arduino.
Update:
mtasic
's example code is quite good, but if the Arduino has sent a partial line wheninWaiting()
is called, you'll get a truncated line. Instead, what you want to do is to put the last complete line intolast_received
, and keep the partial line inbuffer
so that it can be appended to the next time round the loop. Something like this:Regarding use of
readline()
: Here's what the Pyserial documentation has to say (slightly edited for clarity and with a mention to readlines()):which seems quite reasonable to me!