Hey Guys
I have two stepper motors a potentiometer and two buttons, in my code when one button is pressed i can control the position of the stepper motor shafts with the pot, when i press another button the motors spin up and i can control the speed at which they turn.
All is good if i control the the position first and the spin them up, however if i spin them up and down and then control the position the try to go back to "0" first, i know i need to setCurrentPosition to 0 when entering the loop but i cant figure out how to set it only one when entering that part of the code,
sorry i am a noob and my code is not as clean as what i see on here.
Thanks for your help.
#include <AccelStepper.h>
#include <Bounce.h>
AccelStepper motor(1,6,5); //stepper 1
AccelStepper motor1(1,8,9); //stepper 2
#define BUTTON 2 //button 1
#define BUTTON1 11 //button 2
#define ANALOG_IN A2 //slide pot for speed
Bounce bouncer = Bounce( BUTTON,5 );
Bounce bouncer1 = Bounce( BUTTON1,5 );
int sped = analogRead(ANALOG_IN);
const int numReadings = 100; //100 samples for average
int readings[numReadings]; // the readings from the analog input
int index = 0; // the index of the current reading
int total = 0; // the running total
int average = 0; // the average
int inputPin = A2; //slide pot for position
void setup() {
//motor.setMaxSpeed(650);
motor.setAcceleration(3000);
motor.setMinPulseWidth(40);
motor.setCurrentPosition(0);
//motor1.setMaxSpeed(650);
motor1.setAcceleration(2800);
motor1.setMinPulseWidth(40);
motor1.setCurrentPosition(0);
pinMode(BUTTON,INPUT);
for (int thisReading = 0; thisReading < numReadings; thisReading++)
readings[thisReading] = 0;
}
void loop() {
bouncer.update ( );
bouncer1.update ( );
if (bouncer1.read() == LOW && bouncer.read() == HIGH ) { //position loop
// motor.setCurrentPosition(0); ************* where do i put this????
calcmotor();
delay(5);
motor.moveTo(average);
motor.setSpeed(1000);
motor1.moveTo(average);
motor1.setSpeed(1000);
motor.runSpeedToPosition();
motor1.runSpeedToPosition();
}
else{ //speed loop
if (bouncer.read() == LOW) {
motor.move(9999999);
motor1.move(9999999);
}
else {
motor.stop() ;
motor1.stop() ;
}
int sped = analogRead(ANALOG_IN);
int val = map(sped, 0, 1023, 350, 600);
motor.setMaxSpeed(val);
motor1.setMaxSpeed(val);
motor.run();
motor1.run();
}}
void calcmotor(){ //position smoothing calculation
int sped = analogRead(inputPin);
int val = map(sped, 0, 1023, -100, 100);
total= total - readings[index];
// read from the sensor:
readings[index] = val;
// add the reading to the total:
total= total + readings[index];
// advance to the next position in the array:
index = index + 1;
// if we're at the end of the array...
if (index >= numReadings)
// ...wrap around to the beginning:
index = 0;
// calculate the average:
average = total / numReadings;
// send it to the computer as ASCII digits
}