Search code examples
pythonarduinoreadlinepyserial

Pyserial readline() and wait until receives a value to continue


I'm using Pyserial to communicate between python and arduino. I have to wait until the arduino actions are executed before continuing my python loop. I have the arduino print out "done" after it completes its actions. How would I check for this using readline(). I'm trying this at the moment however it never breaks out of the loop:

arduino = serial.Serial(port='COM3', baudrate=9600, timeout=.2)

for coordinate in coordinates:
    c = str(coordinate[0]) + ", " + str(coordinate[1])
    arduino.write(bytes(c, 'utf-8'))
    while arduino.readline() != "Done":
          print(arduino.readline())
void loop() {
  while (!Serial.available()){
    MotorControl(100);
  }
  MotorControl(0);
  String coordinates = Serial.readString();
  int i = coordinates.indexOf(',');
  int x = coordinates.substring(0, i).toInt();
  int y = coordinates.substring(i+1).toInt();

//there will be some other actions here

  Serial.print("Done");

In the terminal I can see that it prints out b'Done'however I don't know how to reference this in my python while loop.


Solution

  • It looks like arduino.readline() is returning bytes but you're comparing it to a str, so the result is always False:

    >>> print("Done" == b"Done")
    False
    

    The simplest solution would be to change "Done" to b"Done", like this:

        while arduino.readline() != b"Done":