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 <LiquidCrystal.h>
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
}
}
}