LED.cpp 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. #include <Arduino.h>
  2. //#define PWMRANGE 255
  3. class LED{
  4. unsigned int _pin;
  5. bool _on;
  6. unsigned long _fadeDurationOn, _fadeDurationOff, _fadeStart, _fadeEnd;
  7. unsigned long getFadeDuration(){
  8. return _on ? _fadeDurationOn : _fadeDurationOff;
  9. }
  10. unsigned long getRemainingFadeTime(){
  11. unsigned long now = millis();
  12. return _fadeEnd >= now ? constrain(_fadeEnd - now, 0, getFadeDuration()) : 0;
  13. }
  14. float getMultiplier() {
  15. float value = getRemainingFadeTime() / (float)getFadeDuration();
  16. return 1.0f - value;
  17. }
  18. float getOutputMultiplier(){
  19. float value = getMultiplier();
  20. return _on ? value : 1.0f - value;
  21. }
  22. void reset(bool on){
  23. if (on == _on)
  24. return;
  25. float oldMultiplier = getMultiplier();
  26. _on = on;
  27. _fadeStart = millis();
  28. _fadeEnd = _fadeStart + (getFadeDuration() * oldMultiplier);
  29. }
  30. public:
  31. LED(unsigned int pin, unsigned long fadeDurationOn, unsigned long fadeDurationOff){
  32. _pin = pin;
  33. pinMode(pin, OUTPUT);
  34. _fadeDurationOn = fadeDurationOn;
  35. _fadeDurationOff = fadeDurationOff;
  36. }
  37. void on(){
  38. reset(true);
  39. }
  40. void off(){
  41. reset(false);
  42. }
  43. void toggle(){
  44. reset(!_on);
  45. }
  46. void loop(){
  47. float multiplier = getOutputMultiplier();
  48. analogWrite(_pin, PWMRANGE * multiplier);
  49. }
  50. };