#include //#define PWMRANGE 255 class LED{ unsigned int _pin; bool _on; unsigned long _fadeDurationOn, _fadeDurationOff, _fadeStart, _fadeEnd; unsigned long getFadeDuration(){ return _on ? _fadeDurationOn : _fadeDurationOff; } unsigned long getRemainingFadeTime(){ unsigned long now = millis(); return _fadeEnd >= now ? constrain(_fadeEnd - now, 0, getFadeDuration()) : 0; } float getMultiplier() { float value = getRemainingFadeTime() / (float)getFadeDuration(); return 1.0f - value; } float getOutputMultiplier(){ float value = getMultiplier(); return _on ? value : 1.0f - value; } void reset(bool on){ if (on == _on) return; float oldMultiplier = getMultiplier(); _on = on; _fadeStart = millis(); _fadeEnd = _fadeStart + (getFadeDuration() * oldMultiplier); } public: LED(unsigned int pin, unsigned long fadeDurationOn, unsigned long fadeDurationOff){ _pin = pin; pinMode(pin, OUTPUT); _fadeDurationOn = fadeDurationOn; _fadeDurationOff = fadeDurationOff; } void on(){ reset(true); } void off(){ reset(false); } void toggle(){ reset(!_on); } void loop(){ float multiplier = getOutputMultiplier(); analogWrite(_pin, PWMRANGE * multiplier); } };