#include <Stepper.h>
// Define the number of steps per revolution for your stepper motor
const int stepsPerRevolution = 50;
// Create a new instance of the Stepper class
Stepper stepper(stepsPerRevolution, 11, 12, 13, 14);
// Button pin
const int buttonPin = 2;
// Variable to store the button state
int buttonState = 0;
// Variable to store the previous button state
int prevButtonState = 0;
void setup() {
// Set the speed of the motor in RPM (Rotations Per Minute)
stepper.setSpeed(60); // 60 RPM
// Set the button pin as input
pinMode(buttonPin, INPUT);
// You can also set the speed in steps per second
// stepper.setSpeed(1000); // 1000 steps per second
// You can adjust other motor parameters here if needed
}
void loop() {
// Read the current button state
buttonState = digitalRead(buttonPin);
// Check if the button has been pressed (transition from HIGH to LOW)
if (buttonState == LOW && prevButtonState == HIGH) {
// Rotate the motor one revolution clockwise
stepper.step(stepsPerRevolution);
// Delay for a moment before rotating in the opposite direction
delay(1000);
// Rotate the motor one revolution counter-clockwise
stepper.step(-stepsPerRevolution);
// Delay for a moment before repeating the loop
delay(1000);
}
// Store the current button state as the previous state for the next iteration
prevButtonState = buttonState;
}