#include "FastLED.h"
#include "Wire.h"
#include "Adafruit_GFX.h"
#include "Adafruit_SSD1306.h"
#include "Encoder.h"
#define LED_STRIP_PIN 6
#define OLED_RESET 7
Adafruit_SSD1306 display(OLED_RESET);
#define ROTARY_ENCODER_PIN_A 2
#define ROTARY_ENCODER_PIN_B 3
#define BUTTON_PIN 12
Encoder myEncoder(ROTARY_ENCODER_PIN_A, ROTARY_ENCODER_PIN_B);
long lastEncoderValue;
unsigned long timerSetting = 0;
unsigned long timerStartTime = 0;
bool timerActive = false;
#define NUM_LEDS 8
#define LED_TYPE WS2812B
#define COLOR_ORDER GRB
CRGB leds[NUM_LEDS];
void setup() {
pinMode(LED_STRIP_PIN, OUTPUT);
display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(WHITE);
pinMode(BUTTON_PIN, INPUT_PULLUP);
lastEncoderValue = myEncoder.read();
FastLED.addLeds<LED_TYPE, LED_STRIP_PIN, COLOR_ORDER>(leds, NUM_LEDS).setCorrection(TypicalLEDStrip);
}
void loop() {
long encoderValue = myEncoder.read();
bool buttonPressed = digitalRead(BUTTON_PIN) == LOW;
if (encoderValue != lastEncoderValue) {
timerSetting += (encoderValue - lastEncoderValue) * 1000;
if (timerSetting < 0) {
timerSetting = 0;
}
timerActive = true;
timerStartTime = millis();
lastEncoderValue = encoderValue;
}
if (buttonPressed) {
while (digitalRead(BUTTON_PIN) == LOW) {
delay(10);
}
resetTimer();
}
updateLEDs();
updateDisplay();
}
void resetTimer() {
timerSetting = 0;
timerActive = false;
fill_solid(leds, NUM_LEDS, CRGB::Black);
FastLED.show();
}
void updateLEDs() {
if (timerActive) {
unsigned long elapsedTime = millis() - timerStartTime;
if (elapsedTime >= timerSetting) {
timerActive = false;
} else {
int percentage = 100 - ((millis() - timerStartTime) * 100 / timerSetting);
int numLitLEDs = map(percentage, 0, 100, 1, NUM_LEDS);
int brightness = map(percentage, 0, 100, 40, 55);
CRGB color;
if (percentage >= 70) {
color = CRGB::Green;
} else if (percentage >= 30) {
color = CRGB::Yellow;
} else if (percentage >= 10) {
color = CRGB::Orange;
} else {
color = CRGB::Red;
}
for (int i = 0; i < NUM_LEDS; i++) {
if (i < numLitLEDs) {
int ledBrightness = map(i, 0, NUM_LEDS - 1, brightness, 255);
leds[i] = color;
leds[i].fadeToBlackBy(255 - ledBrightness);
} else {
leds[i] = CRGB::Black;
}
}
FastLED.show();
}
}
}
void updateDisplay() {
display.clearDisplay();
display.setCursor(0, 0);
if (timerActive) {
int percentage = 100 - ((millis() - timerStartTime) * 100 / timerSetting);
display.print("Timer: ");
display.print(percentage);
display.print("%");
} else {
display.print("Timer: --");
}
display.display();
}