pySerial program doesn't read serial correctly


Question

I have a problem using pySerial, and I don´t know from where to start looking for. I have a 64 bits Windows Seven OS, with Python 2.7.5 (32 bits), and pySerial and Arduino (Arduino working correctly) already installed.

My Arduino code is the following:

// the setup routine runs once when you press reset:
void setup() {                
  // initialize the serial in 19200 baud rate
  Serial.begin(19200);     
}

// the loop routine runs over and over again forever:
void loop() {
  delay(1000);               // wait for a second
  Serial.print("hello");
}

(Arduino conected in COM8, when using Serial Monitor I can see it saluting)

And my PySerial code looks like this:

import serial
import time

arduino = serial.Serial("COM8", 19200)
time.sleep(2)  

while True:
    print arduino.readline()

When I start this script, the program runs, but I can´t see the serial output (I think the configuration in the Python script is OK because if something - e.g. the port - is wrong, it crashes).

I don´t know what to do to find a solution. Can you help me?

1
3
5/22/2013 12:48:32 PM

Accepted Answer

You might try using println instead of print on the Arduino/C side, and/or set a timeout for the serial read on the Python side.

Since serial.readline() waits for a \n, and you never send one using print, the serial read will just wait for a timeout. (But it's a bit more complicated than this, and it's worth reading the docs on readline and EOL.)

If this doesn't work, at least switch readline to just read and print out each character you may (or may not) be reading, but don't make it more complicated by waiting for the \n that readline requires.

From the demo docs:
Be carefully when using readline(). Do specify a timeout when opening the serial port otherwise it could block forever if no newline character is received. Also note that readlines() only works with a timeout. readlines() depends on having a timeout and interprets that as EOF (end of file). It raises an exception if the port is not opened correctly.

6
5/22/2013 1:04:16 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon