Hello! Im working on a project where ive wired 3 buttons to control the speed of a NEMA17 stepper motor. Think Low, Mid and High speed. I have the code written below and it all works but for some reason when i try to increase the Hz over 100, the speed doesnt seem to change and i cant figure out why.
I'm using an arduino nano and a TMC2209 stepper driver and am feeding it 24V. I've also left all the MSI pins unplugged. I'd be so grateful if anyone can shed some light on why i cant increase the speed, thanks so much in advance! I've put the code below.
#include <AccelStepper.h>
#define dir 2
#define stp 3
#define btnLow 6
#define btnMid 7
#define btnHigh 8
const int stepsPerRev = 200;
#define MotorInterfaceType 1
AccelStepper stepper(MotorInterfaceType, stp, dir);
unsigned long runStartTime = 0;
bool running = false;
bool stopping = false;
long initialPosition = 0;
void setup() {
Serial.begin(9600);
pinMode(btnLow, INPUT_PULLUP);
pinMode(btnMid, INPUT_PULLUP);
pinMode(btnHigh, INPUT_PULLUP);
stepper.setAcceleration(2000); // smoother ramp-up/down
Serial.println("Stepper Smooth Stop After 10 Seconds");
}
void loop() {
unsigned long now = millis();
// LOW speed
if (!running && digitalRead(btnLow) == LOW) {
stepper.setMaxSpeed(stepsPerRev * 20); // 4000 steps/sec
long stepsToMove = stepper.maxSpeed() * 10;
stepper.moveTo(stepper.currentPosition() + stepsToMove);
initialPosition = stepper.currentPosition();
runStartTime = now;
running = true;
stopping = false;
Serial.println("Running at LOW speed (20 Hz) for 10s");
delay(200);
}
// MID speed
if (!running && digitalRead(btnMid) == LOW) {
stepper.setMaxSpeed(stepsPerRev * 100); // 10,000 steps/sec
long stepsToMove = stepper.maxSpeed() * 10;
stepper.moveTo(stepper.currentPosition() + stepsToMove);
initialPosition = stepper.currentPosition();
runStartTime = now;
running = true;
stopping = false;
Serial.println("Running at MID speed (50 Hz) for 10s");
delay(200);
}
// HIGH speed
if (!running && digitalRead(btnHigh) == LOW) {
stepper.setMaxSpeed(stepsPerRev * 110); // 20,000 steps/sec
long stepsToMove = stepper.maxSpeed() * 10;
stepper.moveTo(stepper.currentPosition() + stepsToMove);
initialPosition = stepper.currentPosition();
runStartTime = now;
running = true;
stopping = false;
Serial.println("Running at HIGH speed (100 Hz) for 10s");
delay(200);
}
// Initiate deceleration at ~9500ms
if (running && !stopping && (now - runStartTime >= 9500)) {
stepper.stop(); // smooth deceleration
stopping = true;
Serial.println("Initiating smooth stop...");
}
// Once stopped, clean up
if (running && stopping && !stepper.isRunning()) {
running = false;
long stepsMoved = stepper.currentPosition() - initialPosition;
Serial.print("Motor smoothly stopped after ~10s. Steps moved: ");
Serial.println(stepsMoved);
}
// Run stepper
if (running) {
stepper.run();
}
}