#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();
}
}
}