The past few days I've had trouble with a FOR loop iteration within an IF statement.
I have a 12V DC geared motor with magnetic encoder being driven by an L298N motor driver which is controlled by an Arduino. Most of the code works, being that if button 2 is pressed, the motor rotates clockwise; if button 32 is pressed, the motor rotates counter-clockwise.
However, if button 1 is pressed, I want to motor to rotate clockwise to a specified limit (for which position is reported to the Arudino from encoder), then counter clockwise to another specified limit, and continually repeat this back-and-forth sequence. This FOR loop iteration will correctly work if it (the back-and-forth sequence) alone is placed inside the void loop, but if it is nested within the IF statement, it correctly rotates clockwise but then incorrectly rotates counter-clockwise continuously (never returning to the clockwise direction).
The code is below, any help is appreciated and my apologies for the wordy explanation.
#define enA 9
#define in1 6
#define in2 7
const int button1Pin = 8;
const int button2Pin = 12;
const int button3Pin = 13;
int button1State = 0;
int button2State = 0;
int button3State = 0;
int rotDirection = 0;
volatile long temp, counter = 0;
void setup() {
Serial.begin (9600);
pinMode(2, INPUT_PULLUP);
pinMode(3, INPUT_PULLUP);
attachInterrupt(0, ai0, RISING);
attachInterrupt(1, ai1, RISING);
pinMode(enA, OUTPUT);
pinMode(in1, OUTPUT);
pinMode(in2, OUTPUT);
digitalWrite(in1, LOW);
digitalWrite(in2, LOW);
pinMode(button1Pin, INPUT);
pinMode(button2Pin, INPUT);
pinMode(button3Pin, INPUT);
}
void loop() {
analogWrite(enA, 255);
if( counter != temp ){
Serial.println (counter);
temp = counter;
}
button1State = digitalRead(button1Pin);
button2State = digitalRead(button2Pin);
button3State = digitalRead(button3Pin);
if (button1State == HIGH) {
for (counter =0; counter<2000; counter++) {
clockwise();
}
for (counter= 2000; counter>0; counter--){
counterclockwise();
}
}
if (button2State == HIGH) {
clockwise();
}
if (button3State == HIGH) {
counterclockwise();
}
}
void ai0() {
if(digitalRead(3)==LOW) {
counter++;}
else{
counter--;}
}
void ai1() {
if(digitalRead(2)==LOW) {
counter--;}
else{
counter++;}
}
void clockwise () {
digitalWrite(in1, HIGH);
digitalWrite(in2, LOW);
rotDirection = 1;
delay(20);
}
void counterclockwise () {
digitalWrite(in1, LOW);
digitalWrite(in2, HIGH);
rotDirection = 0;
delay(20);
}