#define WOKWI // If this is defined the data are in accordance with the WOKWI stepper (200 steps/revolution)
#define step_pin 3 // Pin 3 connected to Steps pin on EasyDriver
#define dir_pin 2 // Pin 2 connected to Direction pin
#define MS1 5 // Pin 5 connected to MS1 pin
#define MS2 4 // Pin 4 connected to MS2 pin
#define ENABLE 7 // Pin 7 connected to ENABLE pin (active LOW)
#define X_pin A0 // Pin A0 connected to joystick x axis
int direction; // Variable to set Rotation (CW-CCW) of the motor
#ifdef WOKWI
int steps = 100; // Assumes the belt clip is in the Middle
int Positions[5] = {50,75, 100, 125, 150};
#else
int steps = 1025; // Assumes the belt clip is in the Middle
int Positions[5] = {0,512, 1015, 1535, 2050};
#endif
int Thresholds[6] = {0,100,400,600,900,1023};
void setup() {
Serial.begin(115200);
pinMode(MS1, OUTPUT);
pinMode(MS2, OUTPUT);
pinMode(dir_pin, OUTPUT);
pinMode(step_pin, OUTPUT);
pinMode(ENABLE, OUTPUT);
digitalWrite(ENABLE, LOW); // Enable A4988
Serial.println("Enabled!");
delay(5); // Wait for EasyDriver wake up
/* Configure type of Steps on EasyDriver:
// MS1 MS2
//
// LOW LOW = Full Step //
// HIGH LOW = Half Step //
// LOW HIGH = A quarter of Step //
// HIGH HIGH = An eighth of Step //
*/
digitalWrite(MS1, LOW); // Configures to Full Steps
digitalWrite(MS2, LOW); // Configures to Full Steps
Serial.println("Please center Joystick!");
while (!(analogRead(X_pin) > Thresholds[2]+1 && analogRead(X_pin) <= Thresholds[3])){ // if not centered
Serial.print(".");
delay(1000);
}
Serial.println("\nJoystick is centered!");
}
void loop() {
IfWithinThresholdsStepTo(Positions[0], Thresholds[0] , Thresholds[1]);
IfWithinThresholdsStepTo(Positions[1], Thresholds[1]+1, Thresholds[2]);
IfWithinThresholdsStepTo(Positions[2], Thresholds[2]+1, Thresholds[3]);
IfWithinThresholdsStepTo(Positions[3], Thresholds[3]+1, Thresholds[4]);
IfWithinThresholdsStepTo(Positions[4], Thresholds[4]+1, Thresholds[5]);
}
void IfWithinThresholdsStepTo(uint16_t Position,int lowMargin, int highMargin){
while (analogRead(X_pin) > lowMargin && analogRead(X_pin) <= highMargin) {
if (steps < Position) {
digitalWrite(dir_pin, LOW);
digitalWrite(step_pin, HIGH);
delay(1);
digitalWrite(step_pin, LOW);
delay(1);
steps++;
}
if (steps > Position) {
digitalWrite(dir_pin, HIGH);
digitalWrite(step_pin, HIGH);
delay(1);
digitalWrite(step_pin, LOW);
delay(1);
steps--;
}
}
}