How to consistently print data from serial in python


I'm trying to print the data that comes across the serial from an Arduino but I am unable to do so. My attempted code is this:

import serial
import time
s = serial.Serial('/dev/tty.usbmodemfd141',9600)

while 1:
   if s.inWaiting():
      val = s.readline(s.inWaiting())
      print val

Yet after about 30 lines or so are spit out I get the following error message:

Traceback (most recent call last):
  File "", line 7, in <module>
    val = s.readline(s.inWaiting())
  File "build/bdist.macosx-10.8-intel/egg/serial/", line 460, in read
serial.serialutil.SerialException: device reports readiness to read but returned no data (device disconnected?)

I imagine I am using inWaiting incorrectly, but I do not see how to use it any other way.

10/5/2012 1:23:28 AM

Accepted Answer

Have you tried wrapping the readline in a try/except SerialException block? You could then just pass on the SerialException. It could be an issue with the serial driver reporting data in the receive buffer when there is not any, in which case your code will just keep running. Not a great fix, but it may lead you to the correct solution.

except serial.serialutil.SerialException:
    pass # or maybe print s.inWaiting() to identify out how many chars the driver thinks there is
10/5/2012 5:28:02 PM

if you want to simply print the data coming out of the serially connected can simply do it by using readline(). first open the port by using open() then you need to use the readline().

note:/dev/ttyUSB0 is a port number for linux and com0 is windows

here is the code

import serial 

BAUDRATE = 115200
device_name = "ttyUSB0"
tty = device_name
s = serial.Serial("/dev/" + tty, baudrate=BAUDRATE)
print s

    while True:
        line = s.readline()   //after this you can give the sleep time also as time.sleep(1) before that import time module.
        print line

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