Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the equivalent of Serial.available() in pyserial?

When I am trying to read multiple lines of serial data on an Arduino, I use the following idiom:

String message = "";
while (Serial.available()){
    message = message + serial.read()
}

In Arduino C, Serial.available() returns the number of bytes available to be read from the serial buffer (See Docs). What is the equivalent of Serial.available() in python?

For example, if I need to read multiple lines of serial data I would expect to ues the following code:

import serial
ser = serial.Serial('/dev/ttyACM0', 9600, timeout=0.050)
...
while ser.available():
    print ser.readline()
like image 740
Michael Molter Avatar asked Jul 28 '16 19:07

Michael Molter


1 Answers

The property Serial.in_waiting returns "the number of bytes in the receive buffer".

This seems to be the equivalent of Serial.available()'s description: "the number of bytes ... that's already arrived and stored in the serial receive buffer."

Try:

import serial
ser = serial.Serial('/dev/ttyACM0', 9600, timeout=0.050)
...
while ser.in_waiting:  # Or: while ser.inWaiting():
    print ser.readline()

For versions prior to pyserial 3.0, use .inWaiting(). To determine your pyserial version, do this:

import serial
print(serial.__version__)
like image 200
Robᵩ Avatar answered Oct 02 '22 17:10

Robᵩ