#include <Arduino.h>
#include <FastLED.h>
constexpr byte LED_PIN = 21;
constexpr int NUM_LEDS = 16;
CRGB leds[NUM_LEDS];
CRGB colBlack = CRGB(0, 0, 0);
CRGB colRed = CRGB(250, 0, 0);
CRGB colGreen = CRGB(0, 250, 0);
CRGB colBlue = CRGB(0, 0, 250);
CRGB colWhite = CRGB(250, 250, 250);
CRGB colors[5] = {colBlack, colRed, colGreen, colBlue, colWhite};
int actIdx = 0;
int colIdx = 0;
constexpr unsigned long debounceTime{ 30 };
class BtnClass {
private:
byte pin;
byte state;
byte lastState;
unsigned long lastChange;
unsigned long lastPressTime;
public:
void init(byte p) {
pin = p;
pinMode(pin, INPUT_PULLUP);
lastPressTime = 0;
}
unsigned long getLastPressTime() {
return lastPressTime;
};
void reset() {
lastPressTime = 0;
}
boolean pressed() {
byte actState = digitalRead(pin);
if (actState != lastState) {
lastChange = millis();
lastState = actState;
};
if (actState != state && millis() - lastChange > debounceTime) {
state = actState;
if (!state) lastPressTime = lastChange;
return !state;
}
return false;
}
};
constexpr byte maxBtn{ 4 };
constexpr byte btnPins[maxBtn] = { 15, 2, 4, 16 };
BtnClass btn[maxBtn];
void setup() {
Serial.begin(115200);
for (int i = 0; i < maxBtn; i++) {
btn[i].init(btnPins[i]);
}
FastLED.addLeds<WS2812B, LED_PIN, GRB>(leds, NUM_LEDS);
FastLED.setBrightness(255);
setColour(0); // Do the first step here
}
void loop() {
for (int i = 0; i < maxBtn; i++) {
if (btn[i].pressed()) {
Serial.print("Button ");
Serial.print(i + 1);
Serial.println(" pressed");
handle(i);
}
}
}
void setColour(int idx) {
fill_solid(leds, NUM_LEDS, colors[idx]);
FastLED.show();
}
void setPixel(int index) {
for (int i = 0; i < NUM_LEDS; i++) {
leds[i] = colBlack;
}
leds[index] = colWhite;
FastLED.show();
}
void handle(int btId) {
switch (btId) {
case 0:
setColour(0);
break;
case 1:
setColour(colIdx);
colIdx++;
if (colIdx > 4) colIdx = 1;
break;
case 2:
AddIdx(1);
setPixel(actIdx);
break;
case 3:
AddIdx(-1);
setPixel(actIdx);
break;
}
}
void AddIdx(int delta) {
actIdx += delta;
if (actIdx < 0) actIdx = NUM_LEDS - 1;
if (actIdx >= NUM_LEDS) actIdx = 0;
Serial.print("actIdx = ");
Serial.println(actIdx);
}