// Rotary Encoder Inputs
#define CLK 2
#define DT 3
#define SW 4
/*
#include <Wire.h> //ของจริง
#include <LiquidCrystal_I2C.h> //ของจริง
LiquidCrystal_I2C lcd(0x27, 16, 2); //ของจริง
*/
#include <LiquidCrystal_I2C.h> //ของ wokwi
#define I2C_ADDR 0x27 //ของ wokwi
#define LCD_COLUMNS 16 //ของ wokwi
#define LCD_LINES 2 //ของ wokwi
LiquidCrystal_I2C lcd(I2C_ADDR, LCD_COLUMNS, LCD_LINES); //ของ wokwi
int counter = 0;
int currentStateCLK;
int lastStateCLK;
String currentDir ="";
unsigned long lastButtonPress = 0;
void setup() {
//lcd.begin();//ของจริง
lcd.init();//wokwi
// Print a message to the LCD.
lcd.setCursor(1,0);
lcd.print("LOADING");
for(int i = 0;i <=16;i++)
{
lcd.setCursor(i,1);
lcd.write(255);
lcd.setCursor(9,0);
lcd.print(5.88*(i+1));
lcd.setCursor(14,0);
lcd.print("% ");
delay(200);
}
lcd.clear();
// Set encoder pins as inputs
pinMode(CLK,INPUT);
pinMode(DT,INPUT);
pinMode(SW, INPUT_PULLUP);
Serial.begin(9600);
Serial.println("Welcome to the Serial Monitor!");
Serial.println("---------------------------------");
// 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";
}
Serial.print("Direction: ");
Serial.print(currentDir);
Serial.print(" | Counter: ");
Serial.println(counter);
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Direction: ");
lcd.setCursor(10,0);
lcd.print(currentDir);
lcd.setCursor(0,1);
lcd.print("| Counter: ");
lcd.setCursor(10,1);
lcd.print(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 > 50) {
Serial.println("Button pressed!");
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Button pressed!");
}
// Remember last button press event
lastButtonPress = millis();
}
// Put in a slight delay to help debounce the reading
delay(1);
}