Units.h 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. #include <Arduino.h>
  2. #include <inttypes.h>
  3. #ifndef _UNITS_H
  4. #define _UNITS_H
  5. #define COLOR_TEMP_MAX_MIREDS 370
  6. #define COLOR_TEMP_MIN_MIREDS 153
  7. class Units {
  8. public:
  9. template <typename T, typename V>
  10. static T rescale(T value, V newMax, float oldMax = 255.0) {
  11. return round(value * (newMax / oldMax));
  12. }
  13. static uint8_t miredsToBrightness(uint8_t mireds, uint8_t maxValue = 255) {
  14. // MiLight CCT bulbs range from 2700K-6500K, or ~370.3-153.8 mireds. Note
  15. // that mireds are inversely correlated with color temperature.
  16. uint32_t tempMireds = constrain(mireds, COLOR_TEMP_MIN_MIREDS, COLOR_TEMP_MAX_MIREDS);
  17. uint8_t scaledTemp = round(
  18. maxValue*
  19. (tempMireds - COLOR_TEMP_MIN_MIREDS)
  20. /
  21. static_cast<double>(COLOR_TEMP_MAX_MIREDS - COLOR_TEMP_MIN_MIREDS)
  22. );
  23. return (maxValue - scaledTemp);
  24. }
  25. static uint8_t brightnessToMireds(uint8_t value, uint8_t maxValue = 255) {
  26. uint8_t reverseValue = maxValue - value;
  27. uint8_t scaled = rescale(reverseValue, (COLOR_TEMP_MAX_MIREDS - COLOR_TEMP_MIN_MIREDS), maxValue);
  28. return COLOR_TEMP_MIN_MIREDS + scaled;
  29. }
  30. };
  31. #endif