NerdKits - electronics education for a digital generation

You are not logged in. [log in]

NEW: Learning electronics? Ask your questions on the new Electronics Questions & Answers site hosted by CircuitLab.

Microcontroller Programming » Reading from the serial port using python?

February 06, 2011
by lcruz007
lcruz007's Avatar

Hello,

I am sending some values from the MCU to the serial port using:

...
printf_P(PSTR("%d\r\n"), X );

Then I want to read that value using a python script. What's the best way to do this task? I tried reading the characters sent by the serial port using Python but it didn't work very well, it was very unstable (the variable wasn't read 100% of the time). This is my python code, what's wrong with it...?

import serial 
serial = serial.Serial("/dev/ttyUSB0", 115200, timeout=1)

while True:
 data = serial.read()
 if data == 1: print "1"
 if data == 2: print "2"

Thank you!

February 07, 2011
by hevans
(NerdKits Staff)

hevans's Avatar

Hi lcruz,

The code looks fine from this end. Serial communications are not going to be 100% reliable. You need to have code on the receiving side to interpret the values and just ignore things that don't make any sense. Slowing down the rate at which you send data down the serial port might also help.

Humberto

Post a Reply

Please log in to post a reply.

Did you know that a NerdKit can take control of a remote-controlled car? Learn more...