This code works and it can fade three LEDs without any problem, obviously you can even add more of them : )
// Pins Definition
const int button1 = 13;
const int button2 = 12;
const int button3 = 11;
const int redled = 2;
const int greenled = 3;
const int blueled = 4;
// Timing States
unsigned long ElapsedLoopTime;
unsigned long Now;
class LED
{
// Parameters
unsigned long ParamStartFeed = 300;
unsigned long ParamDebounce = 50;
float ParamMinLux = 25.5;
float ParamMaxLux = 255.0;
float ParamFeedRamp;
// Pins
int led;
int buttonpin;
// Status Variables
bool INDownFront;
bool LastINValue;
bool LedStatus;
float Lux = 127.0;
bool Direction = true;
unsigned long LastPressed;
bool INStatus;
bool Pressed;
float Delta;
public:
void Initialize(int pin, int ledpin)
{
led = ledpin;
buttonpin = pin;
pinMode(led, OUTPUT);
pinMode(buttonpin, INPUT);
LastINValue = digitalRead(buttonpin);
LastPressed = millis();
ElapsedLoopTime = millis();
}
void Execute(float ParamFeedRamp)
{
INStatus = digitalRead(buttonpin);
INDownFront = LastINValue && !INStatus;
Pressed = ((Now - LastPressed) > ParamStartFeed) && INStatus;
if (INDownFront && (Now - LastPressed < ParamStartFeed) && (Now - LastPressed > ParamDebounce))
{
LedStatus = !LedStatus;
}
if (!INStatus) LastPressed = Now;
LastINValue = INStatus;
if (Pressed && LedStatus)
{
Delta = (ParamMaxLux - ParamMinLux) * ElapsedLoopTime / ParamFeedRamp;
if (Direction)
{
Lux += Delta;
}
else
{
Lux -= Delta;
}
if (Lux > 255) {
Lux = 255;
Direction = false;
}
if (Lux < 25) {
Lux = 25;
Direction = true;
}
}
analogWrite(led, Lux * LedStatus);
}
};
LED ledblue;
LED ledgreen;
LED ledred;
void setup()
{
Serial.begin(115200);
ledred.Initialize(button3, redled);
ledgreen.Initialize(button2, greenled);
ledblue.Initialize(button1, blueled);
}
void loop()
{
Now = millis();
ledred.Execute(3000); // 3000ms
ledgreen.Execute(3000); // 3000ms
ledblue.Execute(3000); // 3000ms
ElapsedLoopTime = millis() - Now;
}