#include <ezButton.h> // the library to use for SW pin
#include <LiquidCrystal_I2C.h> // Library to use for I2C
#define CLK_PIN 25 // ESP32 pin GPIO25 connected to the rotary encoder's CLK pin
#define DT_PIN 32 // ESP32 pin GPIO26 connected to the rotary encoder's DT pin
#define SW_PIN 33 // ESP32 pin GPIO27 connected to the rotary encoder's SW pin
#define DIRECTION_CW 0 // clockwise direction
#define DIRECTION_CCW 1 // counter-clockwise direction
int counter = 1;
int direction = DIRECTION_CW;
int CLK_state;
int prev_CLK_state;
LiquidCrystal_I2C lcd_1(0x27,16,2); // Parameters I2C
ezButton button(SW_PIN); // create ezButton object that attach to pin 7;
void setup() {
lcd_1.begin(22,21);
lcd_1.init();
lcd_1.init();
lcd_1.backlight();
Serial.begin(9600);
// configure encoder pins as inputs
pinMode(CLK_PIN, INPUT);
pinMode(DT_PIN, INPUT);
button.setDebounceTime(50); // set debounce time to 50 milliseconds
// read the initial state of the rotary encoder's CLK pin
prev_CLK_state = digitalRead(CLK_PIN);
}
void loop() {
lcd_1.setCursor(0, 0);
button.loop(); // MUST call the loop() function first
// read the current state of the rotary encoder's CLK pin
CLK_state = digitalRead(CLK_PIN);
// If the state of CLK is changed, then pulse occurred
// React to only the rising edge (from LOW to HIGH) to avoid double count
if (CLK_state != prev_CLK_state && CLK_state == HIGH) {
// if the DT state is HIGH
// the encoder is rotating in counter-clockwise direction => decrease the counter
if (digitalRead(DT_PIN) == HIGH) {
counter--;
direction = DIRECTION_CCW;
lcd_1.clear();
} else {
// the encoder is rotating in clockwise direction => increase the counter
counter++;
direction = DIRECTION_CW;
lcd_1.clear();
}
}
if(counter<1){
counter=2;
}
if(counter>2){
counter=1;
}
switch(counter){
case 1:
lcd_1.setCursor(0, 0);
lcd_1.print(">OPC 1");
lcd_1.setCursor(0, 1);
lcd_1.print(" OPC 2");
break;
case 2:
lcd_1.setCursor(0, 0);
lcd_1.print(" OPC 1");
lcd_1.setCursor(0, 1);
lcd_1.print(">OPC 2");
break;
}
// save last CLK state
prev_CLK_state = CLK_state;
if (button.isPressed()) {
lcd_1.println("The button is pressed");
}
}