Proposed Arduino Code for Button-Controlled Stepper Motor
#include <Stepper.h>
// STEPPER SETUP
const int stepsPerRevolution = 2048;
const int rpm = 5;
//Pins: IN1, IN3, IN2, IN4
Stepper myStepper(stepsPerRevolution, 8, 10, 9, 11);
// Button + Interrupt Set Up
const int buttonPin = 2; // external interrupt pin INT0
volatile bool buttonPressed = false; // set in ISR
bool motorOn = false; // main motor state
// Interrupt Service Routine: just flag that the button was pressed
void buttonISR() {
buttonPressed = true;
}
void setup() {
myStepper.setSpeed(rpm);
// Button with internal pull-up
pinMode(buttonPin, INPUT_PULLUP);
// Trigger on FALLING edge (HIGH -> LOW when button pressed)
attachInterrupt(digitalPinToInterrupt(buttonPin), buttonISR, FALLING);
}
void loop() {
// Handle button press in main code (not inside ISR)
if (buttonPressed) {
buttonPressed = false; // clear flag
// Simple debounce
static unsigned long lastToggleTime = 0;
unsigned long now = millis();
if (now - lastToggleTime > 200) { // 200 ms debounce
motorOn = !motorOn; // toggle motor state
lastToggleTime = now;
}
}
// If motorOn, keep stepping
if (motorOn) {
myStepper.step(1); // small steps so we can react quickly to button
}
}