#include <Wire.h>
#include <LiquidCrystal_I2C.h>
// Set the LCD address (0x27 is common in Wokwi, adjust if needed)
LiquidCrystal_I2C lcd(0x27, 16, 2);
// Custom block character for meter
byte blockChar[8] = {
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF
};
// Rotary Encoder pins for Raspberry Pi Pico in Wokwi
const int pinCLK = 6; // GP6
const int pinDT = 7; // GP7
const int pinSW = 8; // GP8
long counter = 0; // Use long to prevent overflow
int lastStateCLK;
void setup() {
// Initialize pins with internal pull-ups
pinMode(pinCLK, INPUT_PULLUP);
pinMode(pinDT, INPUT_PULLUP);
pinMode(pinSW, INPUT_PULLUP);
lcd.print("OOOOOOOOOOOOOO");
// Initialize I2C communication (Wokwi uses default I2C0: SDA=GP4, SCL=GP5)
Wire.begin();
// Initialize the LCD
lcd.init();
lcd.begin(16, 2);
lcd.backlight();
lcd.createChar(0, blockChar); // Create custom block character for meter
// Display initial message
lcd.setCursor(0, 0);
lcd.print("Rotary Meter:");
// Read initial state of the rotary encoder
lastStateCLK = digitalRead(pinCLK);
}
void loop() {
int currentStateCLK = digitalRead(pinCLK);
if (currentStateCLK != lastStateCLK) {
if (digitalRead(pinDT) != currentStateCLK) {
counter++; // Clockwise
} else {
counter--; // Counterclockwise
}
drawMeter(counter); // Update LCD with rotary encoder data
}
lastStateCLK = currentStateCLK;
// Reset counter on switch press
if (digitalRead(pinSW) == LOW) {
counter = 0;
drawMeter(counter);
delay(200); // Debounce switch
}
delay(5); // Debounce delay for rotary encoder
}
void drawMeter(long value) {
// Show raw value on top line
lcd.setCursor(0, 0);
lcd.print("Rotary Meter: "); // Clear old text
lcd.setCursor(0, 0);
lcd.print("Rotary Meter: ");
lcd.print(value);
// Show meter bar on second line
lcd.setCursor(0, 1);
const int meterLength = 16;
int valMod = value % 100;
if (valMod < 0) valMod += 100;
int blocks = map(valMod, 0, 100, 0, meterLength);
for (int i = 0; i < meterLength; i++) {
if (i < blocks) {
lcd.write((uint8_t)0); // Custom block character
} else {
lcd.print("_");
}
}
}Loading
pi-pico
pi-pico