#include <AccelStepper.h>
//12V full step 200 pulse/rev, 1.5A
// S1 S2 S3 S4 S5 S6
// NO NO OFF NO OFF NO
// The X Stepper pins
#define STEPPER1_DIR_PIN 3
#define STEPPER1_STEP_PIN 2
AccelStepper stepper1(AccelStepper::DRIVER, STEPPER1_STEP_PIN, STEPPER1_DIR_PIN);
int MaxAcc = 10000;
int MaxSpd = 800;
int State = 0;
int Step = 0;
void setup()
{
stepper1.setMaxSpeed(MaxSpd);
stepper1.setAcceleration(MaxAcc);
stepper1.setCurrentPosition(0);
stepper1.moveTo(1000);
Serial.begin(9600);
delay(2000);
Serial.println("Power ON ");
Serial.print("State = ");
Serial.print(State);
Serial.print("t position = ");
Serial.println(stepper1.currentPosition());
delay(2000);
}
void loop()
{
//Serial.println(stepper1.currentPosition());
switch (State)
{
case 0: //
if (stepper1.distanceToGo() == 0)
{
State =1;
Serial.print("State = ");
Serial.print(State);
Serial.print("t position = ");
Serial.println(stepper1.currentPosition());
delay(1000);
stepper1.moveTo(0);
}
break;
case 1: // your hand is close to the sensor
if (stepper1.distanceToGo() == 0)
{
State = 2;
Serial.print("State = ");
Serial.print(State);
Serial.print("t position = ");
Serial.println(stepper1.currentPosition());
delay(1000);
stepper1.moveTo(2500);
}
break;
case 2: // your hand is a few inches from the sensor
if (stepper1.distanceToGo() == 0)
{
State=3;
Serial.print("State = ");
Serial.print(State);
Serial.print("t position = ");
Serial.println(stepper1.currentPosition());
delay(1000);
stepper1.moveTo(0);
}
break;
case 3: // your hand is nowhere near the sensor
if (stepper1.distanceToGo() == 0)
{
State = 4;
Serial.print("State = ");
Serial.print(State);
Serial.print("t position = ");
Serial.println(stepper1.currentPosition());
delay(1000);
stepper1.moveTo(-1000);
}
break;
case 4: // your hand is nowhere near the sensor
if (stepper1.distanceToGo() == 0)
{
State = 5;
Serial.print("State = ");
Serial.print(State);
Serial.print("t position = ");
Serial.println(stepper1.currentPosition());
delay(1000);
stepper1.moveTo(0);
}
break;
case 5: // your hand is nowhere near the sensor
if (stepper1.distanceToGo() == 0)
{
State = 0;
Serial.print("State = ");
Serial.print(State);
Serial.print("t position = ");
Serial.println(stepper1.currentPosition());
delay(1000);
stepper1.moveTo(-2000);
}
break;
}
stepper1.run();
}
เอาต์พุตแสดงตำแหน่ง ที่เคลื่อนที่ไป โดยจะทำงานวนไปตั้งแต่ stateที่ 0 ถึง state 5