#include <LiquidCrystal_I2C.h>
#define I2C_ADDR 0x27
#define LCD_COLUMNS 20
#define LCD_LINES 4
LiquidCrystal_I2C lcd(I2C_ADDR, LCD_COLUMNS, LCD_LINES);
#define clk 2
#define data 3
int counter = 0;
int State;
int LastState;
void setup() {
lcd.init();
lcd.backlight();
//Define the pins as inputs
pinMode (clk,INPUT);
pinMode (data,INPUT);
Serial.begin (9600); //Start serial com so we could print the value on the serial monitor
// Reads the initial state of the clock pin
LastState = digitalRead(clk);
}
void loop() {
State = digitalRead(clk); // Reads the "current" state of the clock pin
// If the previous and the current state of the clock are different, that means a step has occured
if(State != LastState){
// If the data state is different to the clock state, that means the encoder is rotating clockwise
if (digitalRead(data) != State) {
counter = counter+1;
}else{
counter = counter-1;
}
lcd.setCursor(3, 0);
lcd.print("Position:");
lcd.println(counter);
Serial.print("Position: ");
Serial.println(counter);
}
LastState = State; // Updates the previous state of the clock with the current state
}