#include <FastLED.h>
#include <OneButton.h>
#define NUM_LEDS 16
#define LED_PIN 0
#define buttonPin 5 // Push Button
#define relayPin 2
// Rotary Encoder Inputs
#define inputCLK 4
#define inputDT 3
#define SW_Pin 1 // Encoder Switch
int brightLevel = 100; // Default Brightness
int currentStateCLK;
int previousStateCLK;
bool pressed = false;
bool wasPressed = false;
bool relayToggle = true;
CRGB leds[NUM_LEDS];
uint8_t colorChange = 0;
OneButton btn = OneButton(buttonPin, true, true); // Push Button
OneButton SW = OneButton(SW_Pin, true, true); // Encoder Switch
void setup() {
pinMode(inputCLK, INPUT);
pinMode(inputDT, INPUT);
pinMode(relayPin, OUTPUT);
FastLED.addLeds<WS2812B, LED_PIN, GRB>(leds, NUM_LEDS);
previousStateCLK = digitalRead(inputCLK);
btn.attachClick(nextColor);
}
void loop() {
latch();
currentStateCLK = digitalRead(inputCLK);
if (currentStateCLK != previousStateCLK){
if (digitalRead(inputDT) != currentStateCLK) {
// Ecoder is Rotating Counterclockwise
brightLevel --;
if (brightLevel<12){
brightLevel = 12; // Min Brightness
}
} else {
// Encoder is Rotating Clockwise
brightLevel ++;
if (brightLevel>150){
brightLevel = 150; // Max Brightness
}
}
}
previousStateCLK = currentStateCLK;
FastLED.setBrightness(brightLevel);
switch (colorChange) {
case 0:
red();
break;
case 1:
green();
break;
case 2:
blue();
break;
case 3:
orange();
break;
case 4:
yellow();
break;
case 5:
violet();
break;
case 6:
pink();
break;
case 7:
white();
break;
case 8:
cyan();
break;
}
FastLED.show();
btn.tick();
}
void nextColor() {
colorChange = (colorChange + 1) % 9;
}
// ****** Colors ******
void red(){
fill_solid(leds,NUM_LEDS,CRGB::Red);
}
void green() {
fill_solid(leds, NUM_LEDS, CRGB::Green);
}
void blue() {
fill_solid(leds, NUM_LEDS, CRGB::Blue);
}
void orange(){
fill_solid(leds,NUM_LEDS,CRGB::DarkOrange);
}
void yellow() {
fill_solid(leds, NUM_LEDS, CRGB::Yellow);
}
void violet() {
fill_solid(leds, NUM_LEDS, CRGB::DarkViolet);
}
void pink() {
fill_solid(leds, NUM_LEDS, CRGB::DeepPink);
}
void white() {
fill_solid(leds, NUM_LEDS, CRGB::White);
}
void cyan() {
fill_solid(leds, NUM_LEDS, CRGB::Cyan);
}
void latch(){
wasPressed = pressed;
pressed = digitalRead(SW_Pin);
if (pressed & !wasPressed){
relayToggle = !relayToggle;
}
digitalWrite(relayPin, relayToggle);
}