I have attached the code that I am using to read a rotary encoder using interrupts on both encoder inputs. After trialling serval codes this has been the best one and for what i want and works well. I found this example online and it uses port manipulation (I think that's what it is anyway).
My question is in relation to the line of code below:
reading = PIND & 0xC; //read all eight pin values then strip away all but pinA and pinB's values
I understand that this reads all of the pins on port D, but I don't understand how it only selects pinA (pin2 of arduino) and pinB (pin 3 of arduino) values. Is it something to do with 0xC? From what I've read 0xC is hexadecimal for 12.
I hope this makes sense and I'm just curious to know how it works.
You'll see it when you write 0xC as a binary value: 00001100. Bits 2 and 3 (counting right to left!) are HIGH, in this case that means that only those two bits of PIND have influence on the value of reading, the others don't matter.
From what I've read 0xC is hexadecimal for 12.
Yes, and 12 equals 4 + 8, which are the values of the second and third bit in 00001100.
PS.: You don't need two hardware interrupts to read an encoder! Its pins are usually named A and B, but you an use them as if they were called Clock and Data. Clock must trigger an interrupt, Data is just being read.
Thats great thanks for the help. I wasn't taking into account the "0000" before the "1100" and now it makes sense.
Oh ok that would be good if I only need the interrupt on the clock of the encoder as i need to add a second encoder to the project. I'll have a go at changing the code for use with 2 encoders.