// Define pins for stepper motor and driver
const byte DIR_PIN = 2; // Direction pin
const byte STEP_PIN = 3; // Step pin
const byte EN_PIN = 4; // Enable pin
// Define pins for buttons and LEDs
const byte ON_OFF_PIN = 5; // Button to turn on/off the motor
const byte POT_PIN = A1; // Potentiometer pin for speed control
const byte LED_PINS[] = {7, 8, 9}; // Array of LED pins for speed indicators
const byte MOTOR_LED_PIN = 10; // LED to indicate motor state
// Define motor steps per revolution
const int SPR = 100;
// Define variables to store current state and speed
boolean state = LOW; // Motor state (LOW = off, HIGH = on)
byte speedIndex = 0; // Index of current speed in SPEEDS array
byte stepIndex = 0;
int speedValue = 0; // Value read from potentiometer
void setup() {
Serial.begin(115200);
// Set pin modes
pinMode(DIR_PIN, OUTPUT);
pinMode(STEP_PIN, OUTPUT);
pinMode(EN_PIN, OUTPUT);
pinMode(ON_OFF_PIN, INPUT_PULLUP); // Enable internal pull-up resistor for button
pinMode(POT_PIN, INPUT);
for (byte i = 0; i < sizeof(LED_PINS); i++) {
pinMode(LED_PINS[i], OUTPUT);
}
pinMode(MOTOR_LED_PIN, OUTPUT);
digitalWrite(DIR_PIN, HIGH);
setMotorState(false); // Turn off motor initially
}
void loop() {
static byte prevOnOffState = digitalRead(ON_OFF_PIN);
byte onOffState = digitalRead(ON_OFF_PIN);
// Read potentiometer value
speedValue = analogRead(POT_PIN);
if (onOffState != prevOnOffState) {
delay(50); // Debounce delay
prevOnOffState = onOffState;
if (onOffState == LOW) { // If button is pressed
state = !state; // Toggle motor state
setMotorState(state);
}
}
if (state) {
int interval = map(speedValue, 0, 1023, 5000, 10000); // Map potentiometer value to interval between steps
if (stepIndex < SPR) {
digitalWrite(STEP_PIN, HIGH);
delayMicroseconds(interval/2);
digitalWrite(STEP_PIN, LOW);
delayMicroseconds(interval/2);
stepIndex++;
} else {
digitalWrite(DIR_PIN, !digitalRead(DIR_PIN));
stepIndex = 0;
}
}
}
void setMotorState(boolean state) {
digitalWrite(EN_PIN, !state); // Enable/disable motor driver
digitalWrite(MOTOR_LED_PIN, state); // Turn on/off LED to indicate motor state
setSpeedIndicator(state ? speedIndex : 255); // Turn off all speed indicators when motor is off
}
void setSpeedIndicator(byte speedIndex) {
for (byte i = 0; i < sizeof(LED_PINS); i++) {
digitalWrite(LED_PINS[i], (i == speedIndex));
}
}