led-wolke/LEDWolke.ino

114 lines
2.8 KiB
C++

/*
LED Fading mit NodeMCU v 1.0
*/
class RgbLed {
int ledRedPin;
int ledGreenPin;
int ledBluePin;
byte ledRedIntensityStart;
byte ledGreenIntensityStart;
byte ledBlueIntensityStart;
byte ledRedIntensityCur;
byte ledGreenIntensityCur;
byte ledBlueIntensityCur;
byte ledRedIntensityTo;
byte ledGreenIntensityTo;
byte ledBlueIntensityTo;
long timeStart;
long timeEnd;
public:
RgbLed(int redPin, int greenPin, int bluePin)
{
ledRedPin = redPin;
ledGreenPin = greenPin;
ledBluePin = bluePin;
pinMode(ledRedPin, OUTPUT);
pinMode(ledGreenPin, OUTPUT);
pinMode(ledBluePin, OUTPUT);
ledRedIntensityStart = 0;
ledGreenIntensityStart = 0;
ledBlueIntensityStart = 0;
ledRedIntensityCur = ledRedIntensityStart;
ledGreenIntensityCur = ledGreenIntensityStart;
ledBlueIntensityCur = ledBlueIntensityStart;
ledRedIntensityTo = ledRedIntensityStart;
ledGreenIntensityTo = ledGreenIntensityStart;
ledBlueIntensityTo = ledBlueIntensityStart;
timeStart = 0;
timeEnd = 0;
}
public:
void ChangeColor(byte redIntesity, byte greenIntensity, byte blueIntensity, long duration)
{
if (millis() > timeEnd) {
timeStart = millis();
timeEnd = timeStart + duration;
ledRedIntensityStart = ledRedIntensityCur;
ledGreenIntensityStart = ledGreenIntensityCur;
ledBlueIntensityStart = ledBlueIntensityCur;
ledRedIntensityTo = redIntesity;
ledGreenIntensityTo = greenIntensity;
ledBlueIntensityTo = blueIntensity;
}
}
public:
void Update(long currentMillis)
{
if (currentMillis <= timeEnd) {
ledRedIntensityCur = lerp(ledRedIntensityStart, ledRedIntensityTo, timeStart, timeEnd, currentMillis);
ledGreenIntensityCur = lerp(ledGreenIntensityStart, ledGreenIntensityTo, timeStart, timeEnd, currentMillis);
ledBlueIntensityCur = lerp(ledBlueIntensityStart, ledBlueIntensityTo, timeStart, timeEnd, currentMillis);
UpdateLEDs();
}
}
bool Finished() {
return millis() > timeEnd;
}
byte lerp(byte intensityStart, byte intensityEnd, long timeStart, long timeEnd, long timeCurrent) {
long result = ( ( timeCurrent - timeStart ) * ( intensityEnd - intensityStart) / ( timeEnd - timeStart) ) + intensityStart;
return (byte) result;
}
void UpdateLEDs() {
analogWrite(ledRedPin, ledRedIntensityCur * 4); // correction for NodeMCU 0 - 1023
analogWrite(ledGreenPin, ledGreenIntensityCur * 4);
analogWrite(ledBluePin, ledBlueIntensityCur * 4);
}
};
RgbLed ledStripe(5, 4, 0);
int foo = 0;
void setup() {
Serial.begin(115200);
}
void loop()
{
if (ledStripe.Finished() && foo == 0) {
foo = 1;
ledStripe.ChangeColor(0, 0, 0, 2000);
}
if (ledStripe.Finished() && foo == 1) {
foo = 0;
ledStripe.ChangeColor(255, 255, 255, 2000);
}
ledStripe.Update(millis());
}