const int stepPin = 11;
const int dirPin = 10;
const int LEDR = 5; // Red LED pin
const int LEDB = 4; // Blue LED pin
const int buttonPin = 13; // Button pin
bool processFlag = false; // Flag to indicate process is running
bool lastDirection = true;
unsigned long pressTime = 0;
unsigned long currentTime;
void setup() {
pinMode(LEDR, OUTPUT);
pinMode(LEDB, OUTPUT);
pinMode(buttonPin, INPUT_PULLUP);
pinMode(stepPin, OUTPUT);
pinMode(dirPin, OUTPUT);
}
void stepperMove(int steps, int stepDelay, bool clockWise) {
digitalWrite(dirPin, clockWise); // Set direction
for (int i = 0; i < steps; i++) {
if (!(i % 10)) {
digitalWrite(LEDB, !digitalRead(LEDB));
}
digitalWrite(stepPin, HIGH);
delayMicroseconds(stepDelay);
digitalWrite(stepPin, LOW);
delayMicroseconds(stepDelay);
}
}
void loop() {
currentTime = millis();
static unsigned long debounceTime = 0;
static bool buttonState = HIGH;
static bool lastButtonState = HIGH;
// Debounce the button
bool reading = digitalRead(buttonPin);
if (reading != lastButtonState) {
debounceTime = currentTime;
}
if ((currentTime - debounceTime) > 50) { // 50ms debounce time
if (reading == LOW && buttonState == HIGH && !processFlag) { // ignore button presses if process running
// Button pressed, start the process
pressTime = currentTime;
processFlag = true;
digitalWrite(LEDR, HIGH); // Light red LED
}
buttonState = reading;
}
lastButtonState = reading;
// Handle the process if it's running
if (processFlag) {
stepperMove(200, 64000, lastDirection); // Move stepper 200 steps (1 revolution at full step)
lastDirection = !lastDirection; // reverse direction every button press
digitalWrite(LEDR, LOW); // Turn off red LED after motor stops
digitalWrite(LEDB, LOW); // Turn off blue LED after motor stops
processFlag = false; // Reset process flag
}
}