Updated. I actually found out that the encoder is 12 CPR and not 20.
Here is my updated code.
1st test
This is the output I am getting in one full rotation:
1
4
9
11
12
2nd test
How is it incrementing from 1 to 4 then 9 to 11 and 12.. dont really get it?
Every time gets me the right output which is 12 but the increment are different. why?
2
6
10
12
#define encoderPinA 2
#define encoderPinB 3
#define CPR 20
volatile int counter =0;
volatile boolean flag;
volatile int var_degrees =0;
void setup() {
pinMode(9, OUTPUT);
pinMode(encoderPinA, INPUT_PULLUP);
pinMode(encoderPinB, INPUT_PULLUP);
Serial.begin (9600);
attachInterrupt(digitalPinToInterrupt(encoderPinA), isr_A, CHANGE); //INTERRUPT FOR A
attachInterrupt(digitalPinToInterrupt(encoderPinB), isr_B, CHANGE); //INTERRUPT FOR B
}
void loop() {
if(flag == true){
var_degrees = ((360/20)*counter); // convert from counts to degrees
Serial.println(var_degrees);
flag = false;
}
//Interrupts
void isr_A(){
flag = true;
if(digitalRead(encoderPinA) == HIGH){
if(digitalRead(encoderPinB) == LOW){
counter = counter +1; //COUNTER CLOCK WISE
}
else{
counter = counter -1; //CLOCK WISE
}
}
else{ //IF PIN A IS LOW
if(digitalRead(encoderPinB) == HIGH){
counter = counter +1; //CLOCK WISE
}
else{
counter = counter -1 ; //COUNTER CLOCK WISE
}
}
}
void isr_B(){
flag = true;
if(digitalRead(encoderPinB) == HIGH){
if(digitalRead(encoderPinA) == HIGH){
counter = counter + 1; //COUNTER CLOCK WISE
}
else{
counter = counter -1; //CLOCK WISE
}
}
else{ //IF PIN A IS LOW
if(digitalRead(encoderPinA) == LOW){
counter = counter +1; //CLOCK WISE
}
else{
counter = counter -1 ; //COUNTER CLOCK WISE
}
}
}