Hello. I 've been experimenting with the AccelStepper library which is great by the way! I'm trying to use a Potentiometer to set the position of a stepper motor. Below is my current code.
/*Sketch to use a Potentiometer to step the position of a stepper motor
The stepper should move at a constant speed to each newly set position
*/
#include <AccelStepper.h>
// Setting Motor Connections
const int dirPin = 4; //GPIO Pin4
const int stepPin = 2; //GPIO Pin2
// Create an instance
AccelStepper motor1(AccelStepper::DRIVER, stepPin, dirPin, 0xff, 0xff, false);
// This instance form prevents the interface pins from being initialized SEE SETUP void()
// POT reading must move out of this band to cause motion-avoid jidder
#define DEADBAND 5
// Define the analog pin for reading the control voltage
#define ANALOG_IN A6
void setup() {
Serial.begin(115200);
motor1.setPinsInverted(true, false, true);
motor1.setEnablePin(15);
motor1.disableOutputs();
motor1.setMaxSpeed(400.0);
}
void loop() {
static int oldReading = 0; // old ADC reading
static bool printOnce = false; // print flag
motor1.enableOutputs();
// Read new position - four averages cut noise.
int analog_in = (analogRead(ANALOG_IN) + analogRead(ANALOG_IN) + analogRead(ANALOG_IN) + analogRead(ANALOG_IN)) / 4;
if ((analog_in > (oldReading + DEADBAND)) || (analog_in < (oldReading - DEADBAND))) {
motor1.moveTo((long)analog_in);
motor1.setSpeed(100.0); // set speed MUST be called after calling moveTo -
// moveTo calculates a new speed! Needed if runSpeedToPosition is used.
oldReading = analog_in;
printOnce = true;
}
if (motor1.distanceToGo() != 0) {
motor1.runSpeedToPosition();
}
else if (printOnce == true) {
Serial.print(oldReading);
Serial.print(" ");
Serial.print(motor1.currentPosition());
Serial.print(" ");
Serial.println(motor1.targetPosition());
printOnce = 0;
while (motor1.distanceToGo() == 0){
motor1.disableOutputs();
}
}
}
The problem is when I first run the program, the stepper moves to the position according to the Pot. However, after it reaches that position, if I move the Pot to set a "new" position nothing happens. It's running the program once instead of allowing a new Pot setting to set a new Stepper position, which is my goal.
Any guidance will be greatly appreciated.
Thanks, Brian.