/*
ESP32-C3 + A4988 + LED + Push Button (Return to Original Position)
-----------------------------------------------------------------
Pins:
- STEP: GPIO 5
- DIR: GPIO 4
- LED: GPIO 1 (w/ series resistor to LED, then to GND)
- BUTTON: GPIO 10 (internal pull-up), button from GPIO 10 to GND
Behavior:
1) On button press (HIGH->LOW):
a) Turn LED ON for 10 seconds
b) Turn LED OFF
c) Spin the motor 1000° forward
d) Spin the motor 1000° backward (return to original position)
2) Wait for next press.
*/
#include <Arduino.h>
// Pin assignments
const int STEP_PIN = 5; // A4988 STEP pin
const int DIR_PIN = 4; // A4988 DIR pin
const int BUTTON_PIN = 10; // Push button to GND (with internal pull-up)
const int LED_PIN = 1; // LED with series resistor, then to GND
// Motor configuration
// For a typical 200 step/rev motor:
// 360° = 200 steps
// 1000° = (1000/360) * 200 ≈ 556 steps (rounded)
const int STEPS_PER_REV = 200;
const int STEPS_FOR_1000_DEG = 556; // approximate
const int STEP_DELAY_US = 1000; // microseconds between step transitions
// Variables for button state
bool lastButtonState = HIGH; // pull-up: unpressed = HIGH
bool currentButtonState = HIGH;
void setup() {
Serial.begin(115200);
// Configure stepper driver pins
pinMode(STEP_PIN, OUTPUT);
pinMode(DIR_PIN, OUTPUT);
// Configure LED pin
pinMode(LED_PIN, OUTPUT);
digitalWrite(LED_PIN, LOW); // LED off initially
// Configure button with internal pull-up
pinMode(BUTTON_PIN, INPUT_PULLUP);
Serial.println("System Ready. Press button to begin.");
}
void loop() {
// Read button
currentButtonState = digitalRead(BUTTON_PIN);
// Check for a press: HIGH -> LOW transition
if (lastButtonState == HIGH && currentButtonState == LOW) {
Serial.println("Button pressed. Starting sequence...");
// 1) Turn LED on for 10 seconds
digitalWrite(LED_PIN, HIGH);
Serial.println("LED ON for 10 seconds...");
delay(10000);
// 2) Turn LED off
digitalWrite(LED_PIN, LOW);
Serial.println("LED OFF. Spinning motor 1000° forward...");
// 3) Spin forward 1000°
digitalWrite(DIR_PIN, HIGH); // Forward
for (int stepCount = 0; stepCount < STEPS_FOR_1000_DEG; stepCount++) {
digitalWrite(STEP_PIN, HIGH);
delayMicroseconds(STEP_DELAY_US);
digitalWrite(STEP_PIN, LOW);
delayMicroseconds(STEP_DELAY_US);
}
Serial.println("Forward spin complete. Returning to original position...");
// 4) Spin backward 1000° to return
digitalWrite(DIR_PIN, LOW); // Reverse
for (int stepCount = 0; stepCount < STEPS_FOR_1000_DEG; stepCount++) {
digitalWrite(STEP_PIN, HIGH);
delayMicroseconds(STEP_DELAY_US);
digitalWrite(STEP_PIN, LOW);
delayMicroseconds(STEP_DELAY_US);
}
Serial.println("Returned to original position. Waiting for next press...");
}
lastButtonState = currentButtonState;
// Minimal debounce delay
delay(20);
}