Python Forum

Full Version: Waiting for input from serial port, then move on
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Why doesn't this leave the while loop?


#wait for % and then move on
indata = ""
Counter = 0
while indata != "%":  
  indata = ser.read()
  print(indata)
  Counter +=  1
  if Counter > 5:
   sys.exit("Timed out waiting for Bootloader Active Character. Please close window and try again")
Result:

b''
b''
b'%'
b'%'
b'%'
b'%'
Timed out waiting for Bootloader Active Character. Please close window and try again
serial port reads bytes, "%" is a str.

I don't think you should loop. If you are using pySerial, there is a read_until() command that should work well for you.
inp_data = ser.read_until(b"%")
This will wait forever unless you set a timeout on the port.
ser = serial.Serial(port, baudrate, timeout=1.0, ...)   # Timeout read if wait > 1 second
From your post it looks like you already set a timeout.
Thanks, that did the trick
(Apr-17-2024, 06:45 AM)feistycavities Wrote: [ -> ]The issue with your while loop not closing is because you have an embedded for loop in your code.

The cause was the condition of while. In the code there was the check of equality of
Output:
b"%" == "%"
which never is True. So the loop never break and instead sys.exit() was executed at the end.

Data over Sockets, Serial ports and Pipes are always bytes. Python 2 did not this differentiation, which was a huge problem.