#define BLYNK_TEMPLATE_NAME "Speed Encoder"
#define BLYNK_TEMPLATE_ID "TMPL3AhPfbKps"
#define BLYNK_AUTH_TOKEN "i0_iFnOIVnFZ8DA8EA-MC1qlZNcu61SX"
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <BlynkSimpleEsp32.h>
// WiFi/Blynk
char auth[] = BLYNK_AUTH_TOKEN;
char ssid[] = "Wokwi-GUEST";
char pass[] = "";
// LCD
LiquidCrystal_I2C lcd(0x27, 16, 2);
// Pins
#define CLK_PIN 16
#define DT_PIN 17
#define SW_PIN 5
#define POT_PIN 34
// Encoder variables
volatile int counter = 0;
int lastCLK = HIGH;
String currentDir = "STOP";
int lastButtonState = HIGH;
int lastPotValue = -1;
// ---------------- Setup ----------------
void setup() {
Serial.begin(115200);
// LCD
Wire.begin(21, 22);
lcd.init();
lcd.backlight();
lcd.setCursor(0, 0);
lcd.print("Starting...");
// Encoder pins
pinMode(CLK_PIN, INPUT_PULLUP);
pinMode(DT_PIN, INPUT_PULLUP);
pinMode(SW_PIN, INPUT_PULLUP);
lastCLK = digitalRead(CLK_PIN);
// Blynk
Blynk.begin(auth, ssid, pass);
delay(1000);
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Blynk Ready!");
}
// ---------------- Loop ----------------
void loop() {
Blynk.run();
readEncoder();
readPotentiometer();
readEncoderButton();
}
// ---------------- Encoder ----------------
void readEncoder() {
int clkState = digitalRead(CLK_PIN);
if (clkState != lastCLK) {
// rising edge detected
if (clkState == HIGH) {
int dtState = digitalRead(DT_PIN);
if (dtState != clkState) {
counter++; // CW
currentDir = "CW";
} else {
counter--; // CCW
currentDir = "CCW";
}
// Serial debug
Serial.print("Counter: ");
Serial.print(counter);
Serial.print(" Dir: ");
Serial.println(currentDir);
// LCD update (row 0)
lcd.setCursor(0, 0);
lcd.print("Enc: ");
lcd.print(counter);
lcd.print(" ");
lcd.print(currentDir);
lcd.print(" ");
// Blynk
Blynk.virtualWrite(V0, counter);
}
}
lastCLK = clkState;
}
// ---------------- Potentiometer ----------------
void readPotentiometer() {
int potValue = analogRead(POT_PIN);
int mappedValue = map(potValue, 0, 4095, 0, 100);
if (mappedValue != lastPotValue) {
lcd.setCursor(0, 1);
lcd.print("POT: ");
lcd.print(mappedValue);
lcd.print("% ");
lastPotValue = mappedValue;
// Blynk
Blynk.virtualWrite(V1, mappedValue);
}
}
// ---------------- Encoder Button ----------------
void readEncoderButton() {
int buttonState = digitalRead(SW_PIN);
if (buttonState != lastButtonState) {
if (buttonState == LOW) {
counter = 0;
currentDir = "STOP";
lcd.setCursor(0, 0);
lcd.print("Button Pressed! ");
Blynk.virtualWrite(V2, 1);
delay(300); // debounce
} else {
Blynk.virtualWrite(V2, 0);
}
}
lastButtonState = buttonState;
}