I see a couple of issues.
First:
ser.read() is only going to return 1 byte at a time.
If you specify a count
ser.read(5)
it will read 5 bytes (less if timeout occurrs before 5 bytes arrive.)
If you know that your input is always properly terminated with EOL characters, better way is to use
ser.readline()
That will continue to read characters until an EOL is received.
Second:
Even if you get ser.read() or ser.readline() to return multiple bytes, since you are iterating over the return value, you will still be handling it one byte at a time.
Get rid of the
for line in ser.read():
and just say:
line = ser.readline()
Answer from jwygralak67 on Stack OverflowPython Serial: How to use the read or readline function to read more than 1 character at a time - Stack Overflow
Serial read with python
python - Serial.readString() - how does it work exactly? - Arduino Stack Exchange
arduino - Pyserial doesn't read entire line - Electrical Engineering Stack Exchange
I see a couple of issues.
First:
ser.read() is only going to return 1 byte at a time.
If you specify a count
ser.read(5)
it will read 5 bytes (less if timeout occurrs before 5 bytes arrive.)
If you know that your input is always properly terminated with EOL characters, better way is to use
ser.readline()
That will continue to read characters until an EOL is received.
Second:
Even if you get ser.read() or ser.readline() to return multiple bytes, since you are iterating over the return value, you will still be handling it one byte at a time.
Get rid of the
for line in ser.read():
and just say:
line = ser.readline()
I use this small method to read Arduino serial monitor with Python
import serial
ser = serial.Serial("COM11", 9600)
while True:
cc=str(ser.readline())
print(cc[2:][:-5])
First time posting here, I think I posted the "code" part correctly but didn't know about the output part.
I created a class to help me read and write into an instrument using serial port. However, recently I found an issue that I think it's due to sending multiple write commands and I only need to read when I query the instrument. When I send regular write commands, the instrument outputs text indicating the changes made as shown below:
self.id.write(str.encode("send write command\r"))
time.sleep(1)
self.id.write(str.encode("get status\r"))
output=self.id.read_until(str.encode(">>\r"))When sending the write command, it will output a status as:
>>write command:
Configured state to: 0A
>>
>>get status
status is configured to: BB
What I think it's happening is that when I use the read_until() , it will start reading from the "send write" command instead of the "get status" because when I look at the text captured it corresponds to the "Configured state to: 0A" line.
My question is: How do I get the code to read only from the time I send the "get status" command? I have thought about reading the line when I send the "write command" and not doing anything with it, but I think there might be another option.