Accelstepper: Speed control

Read the forum guidelines to see how to properly post code.
Use the IDE autoformat tool (ctrl-t or Tools, Auto format) before posting code in code tags.

void loop() {
Motor1speed = map((analogRead(speedpot)), 0, 1023, speedmin, speedmax);
step1.setSpeed(Motor1speed);
Serial.println(Motor1speed);
step1.runSpeed();
}

Checking the analog input and printing every time through loop is like adding a 1 to 4 ms delay(). You really do not need to do that cause you can only move the pot so fast. Here I read the pot and print 10 times a second, but call runSpeed() every time through loop(). Note that I changed the pin numbers so I could test on my setup and changed the baud rate to a faster rate. You will need to change the code for your pin numbers.

#include <AccelStepper.h>

int Stepper1Pulse = 2;  // **** for CNC shield
int Stepper1Direction = 5;  // **** for CNC shield
const byte enablePin = 8;   // **** for CNC shield
int speedpot = A0;

int Motor1speed = 0;
int speedmin = 0;
int speedmax = 4000;
AccelStepper step1(1, Stepper1Pulse, Stepper1Direction);

void setup()
{
   step1.setMaxSpeed (speedmax);
   step1.setSpeed(0);
   step1.setAcceleration(500);
   pinMode(enablePin, OUTPUT);  // **** for CNC shield
   digitalWrite(enablePin, LOW);   // **** for CNC shield
   digitalWrite(Stepper1Direction, LOW); // CCW
   Serial.begin(115200); // ************** faster baud rate
   Serial.println("Running: StepperDriverTest");
}

void loop()
{
   static unsigned long timer = 0;
   unsigned long interval = 100;
   if (millis() - timer >= interval)
   {
      timer = millis();

      Motor1speed = map((analogRead(speedpot)), 0, 1023, speedmin, speedmax);
      step1.setSpeed(Motor1speed);
      Serial.println(Motor1speed);
   }
      step1.runSpeed();
}
3 Likes