// Define pin connections
const int buttonPinStartStop = 2; // Push button to start/stop the stepper motor
const int buttonPinMode = 3; // Push button to toggle the mode
const int potentiometerPin = A0; // Analog input for potentiometer
const int motorStepPin = 5; // Step pin for the stepper motor
const int motorDirPin = 4; // Direction pin for the stepper motor
const int motorEnablePin = 6; // Enable pin for the stepper motor
// Define variables
int buttonStateStartStop = 0; // Current state of the start/stop button
int lastButtonStateStartStop = 0; // Previous state of the start/stop button
int buttonStateMode = 0; // Current state of the mode button
int lastButtonStateMode = 0; // Previous state of the mode button
int mode = 0; // 0 for normal mode, 1 for special mode
int potValue = 0; // Potentiometer value for controlling speed
long timer = 0;
bool flag = false;
void setup() {
// Set button pins as input
pinMode(buttonPinStartStop, INPUT_PULLUP);
pinMode(buttonPinMode, INPUT_PULLUP);
// Set motor control pins as outputs
pinMode(motorStepPin, OUTPUT);
pinMode(motorDirPin, OUTPUT);
pinMode(motorEnablePin, OUTPUT);
digitalWrite(motorEnablePin, HIGH); // Disable motor initially
}
void loop() {
// Read the state of the buttons
buttonStateStartStop = digitalRead(buttonPinStartStop);
buttonStateMode = digitalRead(buttonPinMode);
// Check if the start/stop button is pressed
if (buttonStateStartStop != lastButtonStateStartStop) {
if (buttonStateStartStop == LOW) {
// If button is pressed, toggle motor state
if (digitalRead(motorEnablePin)) {
digitalWrite(motorEnablePin, LOW); // Enable motor
} else {
digitalWrite(motorEnablePin, HIGH); // Disable motor
}
delay(50); // Debounce
}
}
lastButtonStateStartStop = buttonStateStartStop;
// Check if the mode button is pressed
if (buttonStateMode != lastButtonStateMode) {
if (buttonStateMode == LOW) {
// If button is pressed, toggle mode
mode = !mode;
if (mode == 1)
timer = millis()-3000;
delay(50); // Debounce
digitalWrite(motorEnablePin, HIGH); // Disable motor
}
}
lastButtonStateMode = buttonStateMode;
// Read the potentiometer value and map it to speed
potValue = analogRead(potentiometerPin);
int speed = map(potValue, 0, 1023, 0, 1000);
// Check if in special mode and execute special functionality
if (mode == 1) {
if (millis() - timer > 3000) {//stop start time in milliseconds
if (!flag) {
digitalWrite(motorEnablePin, LOW); // Enable motor
delay(1); // Delay for stability
flag = true;
} else {
digitalWrite(motorEnablePin, HIGH); // Disable motor
delay(1); // Delay for stability
flag = false;
}
timer = millis();
}
} else {
// In normal mode, set the speed and keep the motor enabled
analogWrite(motorStepPin, speed); // Adjust speed with PWM
}
}