1

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;
}
4

PORTx is the latched value last written there. The external value is found in PINx.

| improve this answer | |
  • So I won't be able to use bitRead if my pins are inputs? – barefootcoder Sep 28 '14 at 21:30
  • You're using bitRead() on the wrong variable. – Ignacio Vazquez-Abrams Sep 28 '14 at 21:36
  • Oh now I understand, I should just use PINB instead of PORTB. Thanks for the help :) – barefootcoder Sep 28 '14 at 21:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.