const int motorPin1 = 6; // Pin 2 of L293
const int motorPin2 = 7; // Pin 7 of L293
const int enablePin= 4;
const byte interruptPin = 2;
const byte encoderPin = 3;
int pos = 0;
int flag = 0;
void setup() {
// put your setup code here, to run once:
pinMode(enablePin,OUTPUT);
digitalWrite(enablePin, HIGH);
pinMode(motorPin1,OUTPUT);
pinMode(motorPin2,OUTPUT);
pinMode(encoderPin,INPUT);
pinMode(interruptPin, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(interruptPin), encoder, RISING);
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
if (flag == 0) {
while (flag<10) {
digitalWrite(motorPin1, HIGH);
digitalWrite(motorPin2, LOW);
delay(200);
Serial.print("The Position is: ");
Serial.println(pos);
flag++;
}
while (flag <20) {
digitalWrite(motorPin1, LOW);
digitalWrite(motorPin2, HIGH);
delay(200);
Serial.print("The Position is: ");
Serial.println(pos);
flag++;
}
}
digitalWrite(motorPin1, LOW);
digitalWrite(motorPin2, LOW);
}
void encoder() {
if(digitalRead(encoderPin)==LOW){
pos++;
}else {
pos--;
}
}
Hello, I am running this simple code (see above) to check if my encoder has any issues. The position that it prints keeps increasing even when enters in the second while loop and the direction of rotation changes. I think once it changes the direction, the position should start decreasing. Could you confirm that it looks like I have an issue with my encoder as the position never stops increasing? Thanks