Optical Incremental Encoder Reading using Arduino UNO I have a HP Optical Incremental Encoder (256 CPR) in which


Pin 1 = A,
Pin 2 = VCC,
Pin 3 = GND,
Pin 8 = B.


I already read and see tutorials for rotary encoder such this one:
https://playground.arduino.cc/Main/RotaryEncoders

I have written a program that is supposed to print out the position of my encoder, however I am only getting zeros in my serial monitor. I want to be able to use interrupts. I would like to actually return the position in degrees of my encoder as we rotate it.

I was able to get it to work. I wasn't connecting my pin properly to my Arduino.

    #include &lt;LiquidCrystal.h&gt;

LiquidCrystal lcd(8, 9, 4, 5, 6, 7);


#define encoderPinA 2
#define encoderPinB 3
#define CPR 256
volatile int counter =0;
volatile boolean flag;

volatile int var_degrees =0;

void setup() {

  pinMode(encoderPinA, INPUT);
  pinMode(encoderPinB, INPUT);
  Serial.begin (9600);
  attachInterrupt(digitalPinToInterrupt(encoderPinA), isr, RISING);
  lcd.clear();

}

void loop() {

   if(flag == true){     
        var_degrees = ((360/256.0)*counter);
        Serial.println(var_degrees);
        lcd.setCursor(0, 1);
        lcd.print("Degrees: ");
        lcd.setCursor(9, 1);
        lcd.print(var_degrees);
        flag = false;
  }

}
//Interrupts 

void isr_2(){
flag = true;
  if(digitalRead(encoderPinA) == HIGH){
    if(digitalRead(encoderPinB) == LOW){
      counter = counter -1; //COUNTER CLOCK WISE
    }
    else{
      counter = counter +1; //CW
    }
  }
  else{
    if(digitalRead(encoderPinB) == LOW){
      counter = counter + 1; //CW
    }
    else{
      counter = counter - 1 ; //CCW
    }
  }
}
You are attaching your interrupt incorrectly. You should not pass in the pin number, but the interrupt number. There is also a handy function that converts a pin to the right interrupt number:

attachInterrupt(digitalPinToInterrupt(pin), ISR, mode);


So, your code should be:

attachInterrupt(digitalPinToInterrupt(encoderPinA), isr,CHANGE);


Also, you should declare your counter variable to be volatile, since it is modified within an ISR, and thus the compiler should not assume that it doesn't change even though the loop() never changes it:

volatile int counter = 0;