#include <U8g2lib.h>
#define ENCODER_OPTIMIZE_INTERRUPTS
#include <Encoder.h>
#include <Wire.h>
// OLED Display Settings
U8G2_SSD1306_128X64_NONAME_F_HW_I2C u8g2(U8G2_R0,U8X8_PIN_NONE);
// Rotary Encoder Settings
Encoder encoder(2, 3);
// RGB LED Pins
int redPin = 9;
int greenPin = 10;
int bluePin = 11;
// Buttons
int button1Pin = 6;
int button2Pin = 7;
// Variables
long encoderValue = 0;
bool button1Pressed = false;
bool button2Pressed = false;
int rgbColorIndex = 0;
void setup() {
// Initialize the OLED display
u8g2.begin();
u8g2.setFont(u8g2_font_profont15_tf);
pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
pinMode(bluePin, OUTPUT);
pinMode(button1Pin, INPUT_PULLUP);
pinMode(button2Pin, INPUT_PULLUP);
u8g2.clearBuffer();
u8g2.setCursor(0, 20);
u8g2.print("Encoder: ");
u8g2.sendBuffer();
}
void loop() {
// Read the rotary encoder
long newEncoderValue = encoder.read();
if (newEncoderValue != encoderValue) {
encoderValue = newEncoderValue;
u8g2.clearBuffer();
u8g2.setCursor(0, 20);
u8g2.print("Encoder: ");
u8g2.print(encoderValue);
u8g2.sendBuffer();
}
// Check button1 press
button1Pressed = !digitalRead(button1Pin);
if (button1Pressed) {
u8g2.clearBuffer();
u8g2.setCursor(0, 20);
u8g2.print("Button 1 Pressed");
u8g2.sendBuffer();
delay(500);
}
// Check button2 press
button2Pressed = !digitalRead(button2Pin);
if (button2Pressed) {
u8g2.clearBuffer();
u8g2.setCursor(0, 20);
u8g2.print("Button 2 Pressed");
u8g2.sendBuffer();
delay(500);
}
// Cycle through RGB LED colors
switch (rgbColorIndex) {
case 0:
analogWrite(redPin, 255);
analogWrite(greenPin, 0);
analogWrite(bluePin, 0);
break;
case 1:
analogWrite(redPin, 0);
analogWrite(greenPin, 255);
analogWrite(bluePin, 0);
break;
case 2:
analogWrite(redPin, 0);
analogWrite(greenPin, 0);
analogWrite(bluePin, 255);
break;
}
delay(1000);
rgbColorIndex = (rgbColorIndex + 1) % 3;
}