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()
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__)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With