/*
Arduino | hardware-help
Stepper Motor Randomly Changing Directions
Sultan June 29, 2025— 7:17 PM
I am using an ESP32, ULN2003, and a 28BYJ-48 Stepper Motor.
I have it set up so if the left button is pressed then it will go
reverse, if the right one pressed it will go forward (also if any
of the two previous cases, the blue led turns on) and if neither
are/aren't pressed it stays still. For some reason it just changes
directions whenever it likes. This is my code:
*/
#include <Stepper.h>
const int STEPS = 2048;
Stepper stepper = Stepper(STEPS, 13, 12, 14, 27);
void setup() {
Serial.begin(9600);
pinMode(26, INPUT_PULLUP);
pinMode(25, INPUT_PULLUP);
pinMode(2, OUTPUT);
stepper.setSpeed(20);
}
void loop() {
int leftState = digitalRead(26);
int rightState = digitalRead(25);
if (leftState == 0 && rightState == 0) {
digitalWrite(2, LOW);
stepper.step(0);
}
else if (leftState == 1 && rightState == 0) {
Serial.println("Turn Left");
digitalWrite(2, HIGH);
stepper.step(-512);
}
else if (leftState == 0 && rightState == 1) {
Serial.println("Turn Right");
digitalWrite(2, HIGH);
stepper.step(512);
}
else if (leftState == 1 && rightState == 1) {
digitalWrite(2, LOW);
stepper.step(0);
}
}