const int buttonPin = 26;
const int stepPin = 12;
const int dirPin = 13;
int buttonState = 0;
int lastButtonState = 0;
bool isRunning = false;
int stepCount = 0;
int maxSteps = 1000; // Set your maximum steps here
int step_per_rev = 200; // Set your step for each rev
void setup () {
pinMode (stepPin,OUTPUT);
pinMode (dirPin,OUTPUT);
pinMode (buttonPin,INPUT);
}
void loop () {
buttonState = digitalRead (buttonPin);
if (buttonState != lastButtonState) {
if (buttonState == HIGH) {
isRunning = !isRunning;
if (!isRunning && stepCount > 0) {
digitalWrite(dirPin, LOW);
while(stepCount > 0) {
for(int i = 0; i < step_per_rev; i++) {
digitalWrite(stepPin, HIGH);
delayMicroseconds(500);
digitalWrite(stepPin, LOW);
delayMicroseconds(500);
stepCount--;
if(stepCount <= 0) {
break;
}
}
}
}
}
delay(50); // debounce delay
}
lastButtonState = buttonState;
if (isRunning && stepCount < maxSteps) {
digitalWrite (dirPin,HIGH);
for(int i = 0; i < step_per_rev; i++) {
digitalWrite (stepPin,HIGH);
delayMicroseconds (500);
digitalWrite (stepPin,LOW);
delayMicroseconds (500);
stepCount++;
if(stepCount >= maxSteps) {
isRunning = false;
break;
}
}
}
}