// For: https://forum.arduino.cc/t/controlling-position-of-stepper-motor-without-limit-switches/1037813/
// This Wokwi project: https://wokwi.com/projects/344507517244539474
#include <Stepper.h>
const int pinLDR = A0;
const int hysteresis = 10;
bool alreadyRotated = false; // true when rotated clockwise
const int stepsPerRevolution = 2048; // change this to fit the number of steps per revolution
const int rolePerMinute = 17; // Adjustable range of 28BYJ-48 stepper is 0~17 rpm
// initialize the stepper library on pins 8 through 11:
Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);
void setup()
{
// initialize the serial port:
Serial.begin(9600);
myStepper.setSpeed(rolePerMinute);
}
void loop()
{
int val = analogRead(pinLDR); // define new variable
if (val < (500 - hysteresis) && !alreadyRotated)
{
Serial.println("Clockwise");
myStepper.step(stepsPerRevolution * 3); // do the steps and wait until ready
alreadyRotated = true;
}
else if (val > (500 + hysteresis) && alreadyRotated)
{
Serial.println("Counterclockwise");
myStepper.step(-stepsPerRevolution * 3);
alreadyRotated = false;
}
delay(500); // slow down the sketch
}