Interrupt in Quadrature Encoders - help


I am doing some robotic control and I am using a quadrature encoder with digital channels A and B. I would like to implement an interrupt every time CHA raises. When CHA raises, check the state of CHB. If channel B is high or low, increment or decrement when necessary.

My code is below, can any possible help me understand why it isn't working. The monitor just shows 0, 0, 0, 0, ... etc.


int CHA = 2; int CHB = 4; volatile int encoderCount = 0;

void setup() { Serial.begin(9600); pinMode(CHB, INPUT); attachInterrupt(CHA, checkDirection, RISING); }

void checkDirection() { int CHB_val = digitalRead(CHB); if (CHB_val == 0) encoderCount = encoderCount + 1; else if (CHB_val == 1) encoderCount = encoderCount - 1; }

void loop() { Serial.println(encoderCount); delay(200);


Please don't forget // to use code tags - the # button when composing.

The code looks OK at a first glance - compare result of digitalRead to LOW and HIGH, not to 0 and 1, since that is more readable and future-proof.

So your quadrature encoder has its own pull-ups does it? If not add this to the setup()

  digitalWrite (CHA, HIGH) ;  // turn on internal pull-ups
  digitalWrite (CHB, HIGH) ;

Your problem is in that attach statement, you don't put a pin number there you put a 0 if wired to pin 2 or 1 if wired to pin 3, those are the only two user interrupt options for a 328p based board.

So change:

attachInterrupt(CHA, checkDirection, RISING);


attachInterrupt(0, checkDirection, RISING);

Or assign the value of 0 to your CHA variable.


There is also a library for this type of device in the Playground that worked for me first time ... after I added the pull up resistors :)