Trouble with attachInterrupt when using break beam sensor for rotary encoder

Hello,

I am trying to build a rotary encoder using a break beam sensor, however I have been unable to get the ISR to function properly.

const byte interruptPin = 2;
volatile int count;

void setup() {
  count = 0;
  pinMode(interruptPin, INPUT_PULLUP);
  attachInterrupt(interruptPin, blink, CHANGE);
  Serial.begin(9600);
}

void loop() {
  Serial.println(count);
}

void blink() {
  count++;
}

any help is much appreciated.

Thanks

Please post a wiring diagram, and explain what you mean by "unable to get the ISR to function properly".

What should happen, and what happens instead?

Please read the documentation on attachInterrupt. You are using it incorrectly. There may be other problems.

Hi. You fell into the common trap of attachInterrupt(). The syntax is as follows:

attachInterrupt(digitalPinToInterrupt(pin), ISR, mode); (recommended)
attachInterrupt(interrupt, ISR, mode); (not recommended)

You used the second version where the first argument is the interrupt number. But you actually put the pin number in there (pin 2). Pin 2 is actually interrupt 0. Thats why they recommend you to use the first method. In your case, it should look like:

attachInterrupt(digitalPinToInterrupt(interruptPin), blink, CHANGE);

Hope that helps.

Hi. Any update on this? Did it solve the problem? If so, can you mark this SOLVED?