#include <Wire.h>
#include <U8x8lib.h>
#include <Encoder.h>
// OLED display settings
U8X8_SSD1306_128X64_NONAME_SW_I2C u8x8(SCL, SDA, U8X8_PIN_NONE);
// Rotary encoder pins
#define ENCODER_PIN_A 2
#define ENCODER_PIN_B 3
#define ENCODER_SWITCH 4
Encoder myEnc(ENCODER_PIN_A, ENCODER_PIN_B);
// Variables
int currentState = 0; // Default state
int storedState = 0;
long oldPosition = -999;
bool switchPressed = false;
unsigned long lastSwitchPressTime = 0;
void setup() {
Serial.begin(9600);
// Initialize OLED display
u8x8.begin();
u8x8.setFont(u8x8_font_chroma48medium8_r);
u8x8.clearDisplay();
// Set encoder switch pin
pinMode(ENCODER_SWITCH, INPUT_PULLUP);
// Display initial state
displayState(storedState);
}
void loop() {
long newPosition = myEnc.read() / 4;
// Update state if the encoder position changes
if (newPosition != oldPosition) {
oldPosition = newPosition;
currentState = (currentState + (newPosition > oldPosition ? 1 : -1) + 3) % 3; // Ensure state is 0, 1, or 2
displayCurrentState(currentState);
}
// Check if encoder switch is pressed
bool encoderSwitchState = digitalRead(ENCODER_SWITCH) == LOW;
if (encoderSwitchState != switchPressed) {
if (encoderSwitchState) {
storedState = currentState; // Store the current state
Serial.print("Stored state: ");
Serial.println(storedState);
displayState(storedState);
}
switchPressed = encoderSwitchState;
}
// Debounce delay
delay(50);
}
// Function to display the current state on the OLED
void displayCurrentState(int state) {
u8x8.clearLine(1);
u8x8.setCursor(0, 1);
u8x8.print("Select: ");
u8x8.print(stateToString(state));
}
// Function to display the stored state on the OLED
void displayState(int state) {
u8x8.clearDisplay();
u8x8.setCursor(0, 1);
u8x8.print(stateToString(state));
}
// Function to convert state to string representation
String stateToString(int state) {
switch (state) {
case 0: return "x1";
case 1: return "x10";
case 2: return "x100";
default: return "Unknown";
}
}