#include <AccelStepper.h>
// The X Stepper pins
#define STEPPER1_DIR_PIN 3
#define STEPPER1_STEP_PIN 2
AccelStepper stepper(AccelStepper::DRIVER, STEPPER1_STEP_PIN, STEPPER1_DIR_PIN);
const int buttonPin = 7; //home switch
int state = 0;
int buttonState = 0;
int MaxAcc = 6000;
int MaxSpd = 4000;
void setup()
{
Serial.begin(9600);
pinMode(buttonPin, INPUT_PULLUP);
stepper.setMaxSpeed(MaxSpd); // ทดลองปรับความเร็ว
stepper.setAcceleration(MaxAcc); // ทดลองปรับความเร่ง
}
void loop()
{
//Serial.println(state);
buttonState = digitalRead(buttonPin);
if((buttonState == HIGH)&&(state == 0))//
{
stepper.setMaxSpeed(MaxSpd); // หมุนช้าเข้าหาสวิตช์ Home
stepper.setAcceleration(MaxAcc);
stepper.setSpeed(-500);
stepper.runSpeed();
}
else if ((buttonState == LOW) &&(state == 0))
{
stepper.setMaxSpeed(MaxSpd);
stepper.setAcceleration(MaxAcc);
stepper.setCurrentPosition(0);
state = 1;
delay(1000);
}
if(state ==1 )
{
stepper.runToNewPosition(12000);
delay(1000);
stepper.runToNewPosition(0);
delay(1000);
}
}