2
votes

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. 
        Serial.print("A");
        delay(60);                            // Argh line!
        stepper.runSpeedToPosition(); 
     }   

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

    stepper.runSpeedToPosition(); 
 }  
1

1 Answers

0
votes

Without delay, the while loop will take "all" your system (CPU) resources, actually delaying the interrupt from the serial line. The 60 is very specific value though.

So an option is to rewrite the loop and test if this helps:

if (stepper.distanceToGo() == 0) { 
    while (true) {         
        if(Serial.available() <= 0) { // Ask Mac for more data. 
            Serial.print("A");
            stepper.runSpeedToPosition();
        } else {
//  the case for (Serial.available() > 0) There's info on the serial line
            character = Serial.read();
            content.concat(character);
            if (character == '\n') break; // Keep reading until newline
            stepper.runSpeedToPosition(); 
        }
    }
}