#include <AccelStepper.h>
//Initialize stepper motor
#define STEPS_PER_REVOLUTION 200 // Change this to match your stepper motor's specification
#define DIR_PIN 5
#define STEP_PIN 18
constexpr int maxSpeed = 2000; // Maximum speed of the stepper motor
constexpr int runAtSpeed = 1000; // Speed of the stepper motor
AccelStepper mystepper(AccelStepper::DRIVER, STEP_PIN, DIR_PIN);
// Initialize push button
const int startButtonPin = 13;
boolean stepperOn = false;
void setup() {
mystepper.setMaxSpeed(maxSpeed);
mystepper.setAcceleration(1000);
mystepper.setSpeed(runAtSpeed);
mystepper.moveTo(STEPS_PER_REVOLUTION);
pinMode(startButtonPin, INPUT_PULLUP);
Serial.begin(9600);
Serial.println("Begin");
}
void handleStepper(){
if (stepperOn){
mystepper.runSpeed();
}
}
void reactOnButton(){
if (buttonReleased()) {
if (stepperOn) {
Serial.println("Button stops");
stopStepper();
} else {
Serial.println("Button starts");
startStepper();
}
}
}
void reactOnSerial(){
if (Serial.available() > 0) {
String command = Serial.readStringUntil('\n');
// Parse command and move stepper motor
if (command.startsWith("s")) {
startStepper(); // Move stepper motor
}
if (command.startsWith("p")) {
stopStepper();
}
}
}
void startStepper() {
Serial.println("Start received");
mystepper.setSpeed(runAtSpeed);
stepperOn = true;
}
void stopStepper() {
Serial.println("Stop received");
mystepper.stop();
stepperOn = false;
}
boolean buttonReleased() {
static unsigned long lastTime = 0;
static int lastState = HIGH;
static int state = HIGH;
boolean returnState = false;
int actState = digitalRead(startButtonPin);
if (actState != lastState) {
lastTime = millis();
lastState = actState;
}
if (millis() - lastTime > 30 && state != lastState) {
state = lastState;
if (state) {
returnState = true;
}
}
return returnState;
}
void loop() {
reactOnButton();
reactOnSerial();
handleStepper();
}