简体   繁体   中英

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.

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":

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM