Hello, I am new to arduino. I have the code shown below to control a stepper motor move that follows a sequence of data points. Is there any way to read the data point like a "for loop" so I don't need to repeat typing the command "stepper.setSpeed, stepper.runSpeed" again and again?
Thanks!
#include <AccelStepper.h>
const int dirPin = 5;
const int stepPin = 6;
// Define motor interface type
#define motorInterfaceType 1
AccelStepper stepper(motorInterfaceType, stepPin, dirPin);
void setup() {
stepper.setMaxSpeed(5000);
//stepper.setAcceleration(5000);
//stepper.setSpeed(100);
}
void loop() {
// Run the motor forward at 250 steps/second until the motor reaches 250 steps:
stepper.setCurrentPosition(0);
while(stepper.currentPosition() != 250)
{
stepper.setSpeed(25);
stepper.runSpeed();
}
stepper.setCurrentPosition(0);
while(stepper.currentPosition() != -650)
{
stepper.setSpeed(-65);
stepper.runSpeed();
}
stepper.setCurrentPosition(0);
while(stepper.currentPosition() != 620)
{
stepper.setSpeed(62);
stepper.runSpeed();
}
stepper.setCurrentPosition(0);
while(stepper.currentPosition() != -190)
{
stepper.setSpeed(-19);
stepper.runSpeed();
}
delay(1000);
}
The data points mean the steps, such as 250, 650, 620. for example the following code means "Run the motor forward at 250 steps/second until the motor reaches 250 steps". I would like to change my code to an easier way instead of keeping writing the whole part as shown below for each movement.
I would recommend taking the setSpeed out of the loop.
#include <AccelStepper.h>
const int dirPin = 5;
const int stepPin = 6;
// Define motor interface type
#define motorInterfaceType 1
AccelStepper stepper(motorInterfaceType, stepPin, dirPin);
struct SpeedPos
{
int position;
int speed;
};
SpeedPos config[] = {{250, 25}, {-650, -65}, {620, 62}, {-190, -19}};
const int configLen = sizeof(config)/sizeof(config[0]);
void setup()
{
stepper.setMaxSpeed(5000);
//stepper.setAcceleration(5000);
//stepper.setSpeed(100);
}
void loop()
{
static int i = 0;
// Run the motor forward at 250 steps/second until the motor reaches 250 steps:
stepper.setCurrentPosition(0);
while(stepper.currentPosition() != config[i].position)
{
stepper.setSpeed(config[i].speed);
stepper.runSpeed();
}
// Go to next position
i++;
if (i == configLen)
{
i = 0;
}
delay(1000);
}