Hello everybody, I am trying to use a rotary encoder with my arduino uno.
Unfortunately I am having many troubles that seems to have no reason to be.
This is the setup:
Arduino with connected a rotary encoder, encoder's pin C to 5V, encoder's pin A and B respectively to PIN 2 and 3 (interrupt). I have added two pulldown resistors (10K?) that connects pins 2 and 3 to ground.
I have just written this simple sketch:
int encoderA = 2;
int encoderB = 3;
void setup() {
pinMode(encoderA, INPUT);
pinMode(encoderB, INPUT);
attachInterrupt(0, doEncoderA, RISING);
attachInterrupt(1, doEncoderB, RISING);
Serial.begin(9600);
Serial.println("Test:");
}
void loop() {
}
void doEncoderB(){
int A = digitalRead(encoderA);
detachInterrupt(1);
if(A == LOW){
Serial.println(0);
}else{
Serial.println(1);
}
attachInterrupt(1,doEncoderBFall,FALLING);
}
void doEncoderBFall(){
int A = digitalRead(encoderA);
detachInterrupt(1);
if(A == HIGH){
Serial.println(2);
}else{
Serial.println(3);
}
attachInterrupt(1,doEncoderB,RISING);
}
void doEncoderA(){
}
What this code should do is to print a pair of numbers, 02 if going clockwise and 13 if going counterclockwise.
And it does, but not always, sometimes I get a 02 03 02 03 12 when turning clockwise and something like 13 12 03 when turning counterclockwise.
This is driving me crazy because it don't make sense at all!!
I was shouting to my arduino and my code when I decided to hook up my oscilloscope to the two signals and what I get is the image attached, each and every single pulse is perfectly identical to the one in the picture, no strange behaviour. So I came up that the problem is in the code.
But it is extremely simple, it's almost bulletproof, what am I doing wrong??
pic_6_2.bmp (1.1 MB)
