I'm controlling a stepper motors speed and direction using the x-axis of a joystick - It works, the joystick alters the motors speed and direction, but something in my code is limiting the top speed of the motor despite setting the MaxSpeed in void setup().
I think there is something wrong with the way I'm asking AccelStepper to update the maxSpeed. But I'm not sure how to fix that. Any help would be greatly appreciated!
The code is as follows:
#include <AccelStepper.h> //accelstepper library
AccelStepper stepper(1, 3, 2);
const byte Analog_X_pin = A1; //x-axis readings
int Analog_X = 0; //x-axis value
void setup()
{
stepper.setMaxSpeed(18000); //SPEED = Steps / second
stepper.setAcceleration(1000); //ACCELERATION = Steps /(second)^2
stepper.setSpeed(18000);
delay(500);
}
void loop()
{
ReadAnalog();
stepper.runSpeed(); //step the motor (this will step the motor by 1 step at each loop indefinitely)
}
void ReadAnalog()
{
Analog_X = analogRead(Analog_X_pin);
stepper.setSpeed(35*(Analog_X-518));
}
My hardware is as follows:
Arduino Uno
a4988 driver (set to 1/16 microsteps)
nema17 motor
Also to note Re: setMaxSpeed being 18000 - I realize that number is technically... unattainable(?)
But to elaborate - When I was originally testing the max speed of the motor was with this setup I made a simplified arduino sketch that only turns the motor with the accelStepper library - I kept increasing the setMaxSpeed until the motor responded with a desired speed and " stepper.setMaxSpeed(18000); " had the motor spinning at that desired speed.
But when I put that into the sketch above, the motor only spins about half as fast. which leads me to believe it's an issue with the way I have my code updating and reading the setMaxSpeed() from the analogRead
gustavrhomas:
But when I put that into the sketch above, the motor only spins about half as fast. which leads me to believe it's an issue with the way I have my code updating and reading the setMaxSpeed() from the analogRead
When attempting to run at maximum speed any code that runs while the stepper is running will slow it down. This is why the simplified sketch runs faster.
Here is one way I use to alleviate this problem.
void loop() {
if (myStepper.Run()) // This works because run() returns true if it has NOT reached the destination
{
// Any code put here will slow the stepper down
// only put code here that has to run while the stepper is running
}
else
{
// All other code
// runs when stepper is not running
}
}