#include "AccelStepper.h"
AccelStepper stepperA (1, 9, 8);
AccelStepper stepperB (1, 5, 4);
AccelStepper stepperC (1, 7, 6);
struct Motor {
AccelStepper *stepper;
byte PinLmtSw;
}
mot [] = {
{ & stepperA, A1, },
{ & stepperB, A2, },
{ & stepperC, A3, },
};
const int Nmot = sizeof(mot)/sizeof(Motor);
// -------------------------------------
struct Cmd {
int motor;
unsigned long msec;
int targPos;
}
cmd [] = {
{ 0, 1000, -1500 },
{ 1, 2000, 1500 },
{ 2, 3000, -1500 },
{ 0, 4000, -250 },
{ 1, 5000, 250 },
{ 2, 6000, -250 },
};
const int Ncmd = sizeof(cmd)/sizeof(Cmd);
int cmdIdx = 0;
char s [90];
// -----------------------------------------------------------------------------
unsigned long msec0;
void loop ()
{
unsigned long msec = millis ();
// check if time to update new position
if (msec - msec0 >= cmd [cmdIdx].msec) {
int motorIdx = cmd [cmdIdx].motor;
int pos = cmd [cmdIdx].targPos;
mot [motorIdx].stepper->moveTo (pos);
if (Ncmd <= ++cmdIdx) {
cmdIdx = 0;
msec0 = msec;
}
sprintf (s, " %8lu msec, motor %d, position %6d", msec, motorIdx, pos);
Serial.println (s);
}
// check position and allow motor to run
for (int n = 0; n < Nmot; n++) {
// at limit switch
if (LOW == digitalRead (mot [n].PinLmtSw))
mot [n].stepper->stop ();
// at position zero but limit switch not active
else if (0 == mot [n].stepper->currentPosition ()) {
mot [n].stepper->move (-1);
mot [n].stepper->run ();
}
// allow motor to run
else
mot [n].stepper->run ();
}
}
// -----------------------------------------------------------------------------
void setup ()
{
Serial.begin (9600);
for (int n = 0; n < Nmot; n++) {
mot [n].stepper->setMaxSpeed (100);
mot [n].stepper->setAcceleration (200);
pinMode (mot [n].PinLmtSw, INPUT_PULLUP);
// "home"
while (HIGH == digitalRead (mot [n].PinLmtSw)) {
mot [n].stepper->move (-1); // toward limtit switch
mot [n].stepper->run ();
}
}
}