Arduino Forum

Topics => Science and Measurement => Topic started by: Bluberries on Mar 12, 2019, 11:41 pm

Title: Trouble with attachInterrupt when using break beam sensor for rotary encoder
Post by: Bluberries on Mar 12, 2019, 11:41 pm
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.

Code: [Select]

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
Title: Re: Trouble with attachInterrupt when using break beam sensor for rotary encoder
Post by: jremington on Mar 13, 2019, 02:02 am
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.
Title: Re: Trouble with attachInterrupt when using break beam sensor for rotary encoder
Post by: freaklabs on Mar 20, 2019, 03:04 pm
Hi. You fell into the common trap of attachInterrupt(). The syntax is as follows:
Code: [Select]
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:
Code: [Select]
attachInterrupt(digitalPinToInterrupt(interruptPin), blink, CHANGE);

Hope that helps.
Title: Re: Trouble with attachInterrupt when using break beam sensor for rotary encoder
Post by: freaklabs on Mar 23, 2019, 02:56 am
Hi. Any update on this? Did it solve the problem? If so, can you mark this SOLVED?