Magnetic coded disc hall encoder troubleshooting

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

That's because you are not detecting all the transistions of the pin. You need your interrupt to fire on every CHANGE of one (or both) of the pins. RISING edge only will not work correctly

So how would the code look? Instead of attachInterrupt(digitalPinToInterrupt(interruptPin), encoder, RISING); should I put attachInterrupt(digitalPinToInterrupt(interruptPin), encoder, CHANGE); ? If not how should it be? Thank you very much

This pin maybe floating if you are not using an external pullup or pulldown resistor. Try making it INPUT_PULLUP like the interrupt pin.

Looks like its working now! Thanks a lot

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.