SimpLedRGB/SimpLedRGB.cpp

116 lines
2.9 KiB
C++

#include "SimpLedRGB.h"
SimpLedRGB::SimpLedRGB(int pinRed, int pinGreen, int pinBlue)
{
this->pin_red = pinRed;
this->pin_green = pinGreen;
this->pin_blue = pinBlue;
}
void SimpLedRGB::begin()
{
pinMode(this->pin_red, OUTPUT);
pinMode(this->pin_green, OUTPUT);
pinMode(this->pin_blue, OUTPUT);
this->setColor(color);
}
void SimpLedRGB::setColor(const Color &color)
{
this->color.red = color.red;
this->color.green = color.green;
this->color.blue = color.blue;
analogWrite(this->pin_red, 255 * color.red);
analogWrite(this->pin_green, 255 * color.green);
analogWrite(this->pin_blue, 255 * color.blue);
}
void SimpLedRGB::translateToColor(const Color &color, int duration_millis)
{
const Color colorStart = {
this->color.red,
this->color.green,
this->color.blue
};
const Color colorDelta = {
color.red - this->color.red,
color.green - this->color.green,
color.blue - this->color.blue
};
long t_start = millis();
long t_end = t_start + duration_millis;
while (millis() < t_end) {
float progress = (float)(millis() - t_start) / (float)duration_millis;
const Color colorCurrent = {
colorStart.red + colorDelta.red * progress,
colorStart.green + colorDelta.green * progress,
colorStart.blue + colorDelta.blue * progress
};
setColor(colorCurrent);
}
setColor(color);
}
void SimpLedRGB::rainbowCycle(int cycleDurationMillis)
{
setColor(COLOR_RED);
delay(cycleDurationMillis);
translateToColor(COLOR_YELLOW, cycleDurationMillis);
delay(cycleDurationMillis);
translateToColor(COLOR_GREEN, cycleDurationMillis);
delay(cycleDurationMillis);
translateToColor(COLOR_CYAN, cycleDurationMillis);
delay(cycleDurationMillis);
translateToColor(COLOR_BLUE, cycleDurationMillis);
delay(cycleDurationMillis);
translateToColor(COLOR_VIOLET, cycleDurationMillis);
delay(cycleDurationMillis);
translateToColor(COLOR_RED, cycleDurationMillis);
}
void SimpLedRGB::candle(const Color &color, float wind = 0.5)
{
int duration = random(250, 6000 - 5000 * wind);
float intensity = (float)random(100 + 400 * wind, 300 + 600 * wind) / 1000.0;
unsigned long start = millis();
unsigned long finish = start + duration;
float progress = 0.0;
while (progress < 1.0) {
progress = (float)(millis() - start) / (float)duration;
float brightness = (1.0 - intensity) + (1.0 + cos(PI * 2 * progress)) * 0.5 * intensity;
setColor(
{
color.red * brightness,
color.green * brightness,
color.blue * brightness,
}
);
}
}
void SimpLedRGB::pulse(const Color &color, float timesPerSecond = 1.0, float amplitudeMin = 0.0, float amplitudeMax = 1.0)
{
float amplitude = (1.0 + sin(PULSE_PER_SECOND * millis() * timesPerSecond)) / 2.0;
float brightness = amplitudeMin + (amplitudeMax - amplitudeMin) * amplitude;
setColor({
color.red * brightness,
color.green * brightness,
color.blue * brightness
});
}