There are (potentially) two reasons why this doesn't block as required:
- Serial communication is buffered, so as long as the length of the data passed to
Serial.write()
is smaller than the buffer this call can return before the data is read by the Arduino sketch. In fact, depending on the length of the data and the size of the buffer, several calls toSerial.write()
could complete before the Arduino completes any reads. - The Arduino sketch may not block until the stepper motor has completed its movement. It would be useful to see the sketch to determine whether this is the case.
Sleeping between calls can help but even if you can get this to work you'll likely experience odd, non-reproducible behavior.
The solution to both the problems above is to synchronize the actions in your code. For the serial communication this can be achieved by sending a 'finished' message back from the Arduino sketch to the python script which will read from the serial port until it receives this message. How to synchronize the stepper motor with the Arduino sketch (if needed) will depend on how the Arduino to stepper motor communication is coded.