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;
}
1 Answer 1
PORTx
is the latched value last written there. The external value is found in PINx
.
-
So I won't be able to use bitRead if my pins are inputs?barefootcoder– barefootcoder2014年09月28日 21:30:40 +00:00Commented Sep 28, 2014 at 21:30
-
You're using
bitRead()
on the wrong variable.Ignacio Vazquez-Abrams– Ignacio Vazquez-Abrams2014年09月28日 21:36:09 +00:00Commented Sep 28, 2014 at 21:36 -
Oh now I understand, I should just use
PINB
instead ofPORTB
. Thanks for the help :)barefootcoder– barefootcoder2014年09月28日 21:54:24 +00:00Commented Sep 28, 2014 at 21:54
Explore related questions
See similar questions with these tags.