/*
Forum: https://forum.arduino.cc/t/oled-rotary-encoder/1175366
Wokwi: https://wokwi.com/projects/377762218537644033
*/
//Screen
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
//Rotary Encoder
// Rotary Encoder Inputs
#define inputCLK 4
#define inputDT 5
String encdir = ""; //String to be populated with either ClockWise or CounterClockWise
//Variables
int Length = 20;
int oldLength = 0;
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);
void setup() {
Serial.begin(9600);
display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
display.clearDisplay();
//RotaryEncoder
// Set encoder pins as inputs
pinMode(inputCLK, INPUT);
pinMode(inputDT, INPUT);
}
void loop() {
readEncoder();
printToDisplay();
}
void readEncoder() {
static int previousStateCLK = HIGH; // Store the previous state for the next call of readEncoder()
//Rotary Encoder
// Read the current state of inputCLK
int currentStateCLK = digitalRead(inputCLK);
// If the previous and the current state of the inputCLK are different then a pulse has occured
if (currentStateCLK != previousStateCLK) {
int dtValue = digitalRead(inputDT);
if (currentStateCLK == LOW && dtValue == HIGH) {
// Encoder is rotating clockwise
Length++;
}
if (currentStateCLK == LOW && dtValue == LOW) {
// Encoder is rotating counterclockwise
Length--;
if (Length < 0) {
Length = 0;
}
};
}
// Update previousStateCLK with the current state
previousStateCLK = currentStateCLK;
}
void printToDisplay() {
if (Length != oldLength) {
//Oled
oldLength = Length;
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(WHITE);
//Timer
display.setCursor(0, 10);
display.print("Timer - ");
display.print(Length);
display.println(" Minutes");
display.display();
}
}