Units.h 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  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 miredsToWhiteVal(uint16_t mireds, uint8_t maxValue = 255) {
  14. // MiLight CCT bulbs range from 2700K-6500K, or ~370.3-153.8 mireds.
  15. uint32_t tempMireds = constrain(mireds, COLOR_TEMP_MIN_MIREDS, COLOR_TEMP_MAX_MIREDS);
  16. uint8_t scaledTemp = round(
  17. maxValue*
  18. (tempMireds - COLOR_TEMP_MIN_MIREDS)
  19. /
  20. static_cast<double>(COLOR_TEMP_MAX_MIREDS - COLOR_TEMP_MIN_MIREDS)
  21. );
  22. return scaledTemp;
  23. }
  24. static uint16_t whiteValToMireds(uint8_t value, uint8_t maxValue = 255) {
  25. uint8_t reverseValue = maxValue - value;
  26. uint16_t scaled = rescale<uint16_t, uint16_t>(reverseValue, (COLOR_TEMP_MAX_MIREDS - COLOR_TEMP_MIN_MIREDS), maxValue);
  27. return COLOR_TEMP_MIN_MIREDS + scaled;
  28. }
  29. };
  30. #endif