#include <LiquidCrystal_I2C.h>
#include <Wire.h>
LiquidCrystal_I2C lcd(0x27,16,2); // set the LCD address to 0x27 for a 16 chars and 2 line display
// Rotary Encoder Inputs
#define CLK 2
#define DT 3
#define SW 4
int counter = 0;
int currentStateCLK;
int lastStateCLK;
String currentDir ="";
unsigned long lastButtonPress = 0;
void setup() {
lcd.init(); // initialize the lcd
// Print a message to the LCD.
lcd.backlight();
// Set encoder pins as inputs
pinMode(CLK,INPUT);
pinMode(DT,INPUT);
pinMode(SW, INPUT_PULLUP);
// Setup Serial Monitor
Serial.begin(9600);
Serial.println("BE2222GIN");
// Read the initial state of CLK
lastStateCLK = digitalRead(CLK);
}
void loop() {
// Read the current state of CLK
currentStateCLK = digitalRead(CLK);
// If last and current state of CLK are different, then pulse occurred
// React to only 1 state change to avoid double count
if (currentStateCLK != lastStateCLK && currentStateCLK == 1){
// If the DT state is different than the CLK state then
// the encoder is rotating CCW so decrement
if (digitalRead(DT) != currentStateCLK) {
counter --;
currentDir ="CCW";
} else {
// Encoder is rotating CW so increment
counter ++;
currentDir ="CW";
}
lcd.setCursor(3,0);
lcd.print("Direction: ");
lcd.setCursor(8,1);
lcd.println(counter);
Serial.print("Direction: ");
Serial.print(currentDir);
Serial.print(" | Counter: ");
Serial.println(counter);
}
// Remember last CLK state
lastStateCLK = currentStateCLK;
// Read the button state
int btnState = digitalRead(SW);
//If we detect LOW signal, button is pressed
if (btnState == LOW) {
//if 50ms have passed since last LOW pulse, it means that the
//button has been pressed, released and pressed again
if (millis() - lastButtonPress > 100) {
lcd.setCursor(0,1);
lcd.println("Button pressed!");
Serial.println("Button pressed!");
delay(500);
lcd.clear();
lcd.setCursor(3,0);
lcd.println("Direction: ");
counter=0;
lcd.setCursor(8,1);
lcd.println(counter);
}
// Remember last button press event
lastButtonPress = millis();
}
if (counter >= 9){
counter = 9;
}
if (counter <= 1){
counter = 1;
}
// Put in a slight delay to help debounce the reading
delay(1);
}