Timing Issue Using PySerial with Arduino Uno

Here’s the big picture:

I’m trying to control a stepper motor by recording a set of positions and then playing them back. To control the steppers I am using AccelStepper.

Since the movement data is large I need to store it on my Mac and send it over to the Arduino using the Serial connection.

Also, I can’t afford delays because of the way AccelStepper works.

Here’s the issue:

The code below works when I insert a delay of about 60ms or more. However, this screws up AccelStepper.

My understanding of this is that the first while loop “listens” to the serial line. If there is nothing to read, I send an ‘A’ to the Mac to request some data. This loop breaks when there is data available to read.

The second loop reads the serial line until encountering a newline character. This code works with the delay and does not without a delay.

Does that make sense? Thank-you.


if (stepper.distanceToGo() == 0)
while (Serial.available() <= 0) { // Ask Mac for more data.
delay(60); // Argh line!

while(Serial.available() > 0) { // There’s info on the serial line
character = Serial.read();
if (character == ‘\n’) break; // Keep reading until newline


Small correction...

If there is nothing to read, I send an [u]fill the outbound buffer with[/u] 'A' to the Mac [u]then continuously block until there is space to queue another 'A'[/u] to request some data.

Does that bring clarity?

You should not be requesting data just because there is no data in the input buffer. You should be requesting data when data is needed - and only requesting it once.

I have a somewhat similar project (controlling 3 steppers on a small lathe via Python).

My PC sends data - less than 64 bytes so it all fits in the input buffer.

When the Arduino is ready it takes that data from the buffer and then requests more data. While the PC is sending the next chunk of data the Arduino uses the data that it has just taken from the buffer. That way the serial transmission takes place in the background without wasting any Arduino time.