Simple Serial Question..

Status
Not open for further replies.

JohnPunnett

Active member
Hi All, I am trying to read some data over serial port using a python prog on my laptop. I am basically reading an analog port on Teensy & sending the data to Serial monitor every 1/2 sec using:

int value = analogRead(analogInPin);
Serial.println(value);

This all works fine & I can see the analog data in Serial Monitor tool on IDE.

I have written a very basic Python 3 prog to read & display this data as follows:

import serial
import time

ser = serial.Serial('COM5', 9600)

while 1:
try:
line = ser.readline()
print(line)
time.sleep(1)


Whenever I run the Python 3 prog I get error:

SyntaxError: unexpected EOF while parsing

I have spent ages googling this but cant get pass this first hurdle. Eventually I want to plot data on my laptop but need to be able to read it first..


I'm sure I am missing something simple but banging my head at the moment.

Thks, John
 
I don't speak Python, so can't help with that.

But for a quick way to plot the data, try Tools > Serial Plotter. :)
 
The error most likely means that your program couldn't open the serial port. Are you sure that nothing else is using the port at the same time (e.g. the serial monitor)?
 
I also don't write Python, but do occasionally look at is as some ROS nodes use it. I assume you have pyserial installed?

If I remember correctly python uses indention to control loops and the like. Can not see much here as I don't believe
your code fragment is shown using code blocks and so all of your indention is not shown.

One thing that I wonder is you are using the try: I would expect that there would be something like an except:
to handle any errors...
 
Hi All, Many thanks for your help. OK I managed to now get data being displayed in my Python prog using following:

import serial
import time

ser = serial.Serial('COM5', 115200, timeout=5)



while True:
line = ser.readline()
data = line.decode('utf-8')
print(data)
time.sleep(.01)

I just need to figure out now how to get the streaming data into MatPlotLib to display as graph...

Out of interest when the teensy sends serial data it sends it with lots of other characters - is there a way to just send the analog values as integers without all the slashes/n/cr etc....
 
Last edited:
It's not sending slashes, it's sending control characters (like \n, newline). These are appearing because you used println rather than print.

But! You need delimiters between your numbers, right? So 123 followed by 123 doesn't appear to be 123123...
 
Status
Not open for further replies.
Back
Top