How to create an array of AccelSteppers

329 views
Skip to first unread message

Harrzack

unread,
May 8, 2018, 9:03:44 AM5/8/18
to accelstepper
My 4-motor project is FINALLY working - thanks to all for help given.

Would like to be able to put the 4 drivers into an array as the operations are quite repetitive.

What would be the setup (if possible) so I could refer to AS functions like "stepper[i].Run" ?
I'm guessing I'd have to get the actual AS object into the array, but not sure of syntax.

gregor

unread,
May 8, 2018, 9:28:25 AM5/8/18
to accelstepper
Hi,

untested code below.
#include <AccelStepper.h>

#define NUM_STEPPERS 4

//define an array of stepper pointers. initialize the pointer to NULL (null pointer) for safety (see below)
AccelStepper *steppers[NUM_STEPPERS] = {NULL, NULL, NULL, NULL};

void setup()
{
 
//create accelStepper objects.
  steppers
[0] = new AccelStepper(); // Defaults to AccelStepper::FULL4WIRE (4 pins) on 2, 3, 4, 5
  steppers
[1] = new AccelStepper(AccelStepper::FULL4WIRE, 6, 7, 8, 9);
  steppers
[3] = new AccelStepper(AccelStepper::FULL2WIRE, 10, 11);

 
if (steppers[0])  //if AccelStepper object was successfully created
 
{
    steppers
[0]->setMaxSpeed(200.0);
    steppers
[0]->setAcceleration(100.0);
    steppers
[0]->moveTo(24);
 
}
 
 
if (steppers[1])
 
{
    steppers
[1]->setMaxSpeed(300.0);
    steppers
[1]->setAcceleration(100.0);
    steppers
[1]->moveTo(1000000);
 
}

 
//I have intentionally "forgot" to create an AccelStepper object for steppers[2] to demonstate the safety measure below
 
 
if (steppers[3])
 
{
    steppers
[3]->setMaxSpeed(300.0);
    steppers
[3]->setAcceleration(100.0);
    steppers
[3]->moveTo(1000000);
 
}
}
void loop()
{
 
for (uint8_t i = 0; i < NUM_STEPPERS; i++)
 
{
   
//if a pointer in the array points at NULL (does not point to an AccelStepper object) the code is not executed.
   
//this code will be skipped for steppers[2]
   
if (steppers[i])
   
{
     
// Change direction at the limits
     
if (steppers[i]->distanceToGo() == 0)
        steppers
[i]->moveTo(-steppers[i]->currentPosition());

      steppers
[i]->run();
   
}
 
}
}

Harrzack

unread,
May 8, 2018, 4:54:34 PM5/8/18
to accelstepper
Gregor - thanks for the code!  Looks good - close to what I thought it should be!

=Alan R.
Reply all
Reply to author
Forward
0 new messages