I am trying to read from a quadrature rotary encoder using an Arduino UNO R3. This is done by connecting the encoder's channel A pin to the Arduino interrupt 0 pin (digital IO pin 2). Inside the interrupt routine I then read the value of channel B (connected to digital IO pin 8) to determine the direction of rotation.
I am able to read the correct value of channel B using the digitalRead() function, but when I use bitRead() it always gives me a 0. As far as I know digital IO pin 8 is mapped to PORTB bit 0, so I am using bitRead(PORTB, 0) to read the bit. I also tried to read all of the other pins, but all of them show 0, except the LED at pin 13, which shows 0s and 1s when it gets toggled (It is also the only pin defined to be an OUTPUT pin, whereas the encoder uses INPUT pins).
Below is my code:
int channelA = 0;
int channelB = 8;
volatile int rotateNumber = 0;
volatile boolean interrupted = false;
void setup() {
Serial.begin(115200);
attachInterrupt(channelA, rotate, RISING);
pinMode(channelB, INPUT);
}
void loop() {
if(interrupted){
Serial.println(rotateNumber)
interrupted = false;
}
}
void rotate(){
if(bitRead(PORTB, 0) == 1)
rotateNumber++;
else
rotateNumber--;
interrupted = true;
}