/*
https://forum.arduino.cc/t/dmx-lighting-help/1198060/10
*/
#define BTN_PIN 2
#define RED_PIN 6
#define GREEN_PIN 5
#define BLUE_PIN 3
//used in loop and fadeleds..
unsigned long now;
//loops vars for button debouncing/state..
unsigned long lastPush;
int intervalPush = 50;
byte btnState = 1;
//fading state toggles with each button press..
bool fading = false;
//vars used in FadeLeds..
unsigned long lastCycle;
int intervalCycle = 5;
byte state = 0;
int counter = 0;
void setup() {
Serial.begin(115200);
Serial.println("Ready..");
pinMode(BTN_PIN, INPUT_PULLUP);
}
void loop() {
now = millis();
if (now - lastPush >= intervalPush) {
byte b = digitalRead(BTN_PIN);
if (b != btnState) {
lastPush = now;
btnState = b;
if (btnState == LOW) {
fading = !fading;
if (!fading) {
analogWrite(RED_PIN, 0);
analogWrite(GREEN_PIN, 0);
analogWrite(BLUE_PIN, 0);
} else {
analogWrite(RED_PIN, 255);
state = 0;
counter = 0;
}
}
}
}
if (fading) {
FadeLeds();
}
}
void FadeLeds() {
if (now - lastCycle >= intervalCycle) {
lastCycle = now;
switch (state) {
case 0: if (counter <= 255) {
analogWrite(BLUE_PIN, counter);
counter++;
} else {
state++;
counter = 255;
}
break;
case 1: if (counter > 1) {
analogWrite(RED_PIN, counter);
counter--;
} else {
state++;
counter = 0;
}
break;
case 2: if (counter <= 255) {
analogWrite(GREEN_PIN, counter);
counter++;
} else {
state++;
counter = 255;
}
break;
case 3: if (counter > 1) {
analogWrite(BLUE_PIN, counter);
counter--;
} else {
state++;
counter = 0;
}
break;
case 4: if (counter <= 255) {
analogWrite(RED_PIN, counter);
counter++;
} else {
state++;
counter = 255;
}
break;
case 5: if (counter > 1) {
analogWrite(GREEN_PIN, counter);
counter--;
} else {
state = 0;
counter = 0;
}
break;
}
}
}