// https://wokwi.com/projects/409789859230923777
// for https://forum.arduino.cc/t/stepper-control-with-buttons-for-both-directions-loop-for-positioning/1304119/3
// 240905_2_stepper_2_buttons.ino
// 240905: currently running with ext. power supply 5V.
int Pin1 = 6;//IN1 is connected to 6
int Pin2 = 7;//IN2 is connected to 7
int Pin3 = 8;//IN3 is connected to 8
int Pin4 = 9;//IN4 is connected to 9
int switchCW = 4; //define input pin for CW push button
int switchCCW = 5; //define input pin for CCW push button
int ledCW = 2; // output pin for CW LED
int ledCCW = 3; // output pin for CCW LED
// 8 half-steps + off:
int pole1[] = {0, 0, 0, 0, 0, 1, 1, 1, 0}; //pole1, 8 step values
int pole2[] = {0, 0, 0, 1, 1, 1, 0, 0, 0}; //pole2, 8 step values
int pole3[] = {0, 1, 1, 1, 0, 0, 0, 0, 0}; //pole3, 8 step values
int pole4[] = {1, 1, 0, 0, 0, 0, 0, 1, 0}; //pole4, 8 step values
int poleStep = 0;
int dirStatus = 3;// stores direction status 3= stop (do not change)
void setup()
{
pinMode(Pin1, OUTPUT);//define pin for ULN2003 in1
pinMode(Pin2, OUTPUT);//define pin for ULN2003 in2
pinMode(Pin3, OUTPUT);//define pin for ULN2003 in3
pinMode(Pin4, OUTPUT);//define pin for ULN2003 in4
pinMode(switchCW, INPUT_PULLUP);
pinMode(switchCCW, INPUT_PULLUP);
pinMode(ledCW, OUTPUT);
pinMode(ledCCW, OUTPUT);
}
void loop()
{
if (digitalRead(switchCCW) == LOW)
{
dirStatus = 1;
} else if (digitalRead(switchCW) == LOW)
{
dirStatus = 2;
} else
{
dirStatus = 3;
}
if (dirStatus == 1) { // Forward
digitalWrite(ledCW, HIGH);
poleStep++;
driveStepper(poleStep);
} else if (dirStatus == 2) { // Reverse
digitalWrite(ledCCW, HIGH);
poleStep--;
driveStepper(poleStep);
} else {
driveStepper(8);
}
if (poleStep > 7) {
poleStep = 0;
}
if (poleStep < 0) {
poleStep = 7;
}
delay(3);
}// loop
/*
@brief sends signal to the motor
@param "c" is integer representing the pole of motor
@return does not return anything
*/
void driveStepper(int c)
{
digitalWrite(Pin1, pole1[c]);
digitalWrite(Pin2, pole2[c]);
digitalWrite(Pin3, pole3[c]);
digitalWrite(Pin4, pole4[c]);
}//driveStepper end here