ESP32 Native version of Blinky, featureful controller code for WS2811/WS2812/NeoPixels
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

77 lines
2.3KB

  1. static const char *TAG = "leds";
  2. #include <esp_log.h>
  3. #include "leds.hpp"
  4. #include "utils.hpp"
  5. static inline uint8_t mix(int l, int r, Fixed x) {
  6. return ((l << shift) + (x * (r - l))) >> shift;
  7. }
  8. Color Gradient::at(Fixed x) const {
  9. int i_left = (x * n_colors) >> shift;
  10. int i_right = i_left < n_colors - 1 ? i_left + 1 : 0;
  11. Fixed ratio = (x * n_colors) - (i_left << shift);
  12. //ESP_LOGI(TAG, "at(%d) = %d between %d and %d", x, ratio, i_left, i_right);
  13. Color cl = colors[i_left];
  14. Color cr = colors[i_right];
  15. Color color = {
  16. mix(cl.r, cr.r, ratio),
  17. mix(cl.g, cr.g, ratio),
  18. mix(cl.b, cr.b, ratio)
  19. };
  20. /*ESP_LOGI(TAG, "(%d, %d, %d) %f (%d, %d, %d) -> (%d, %d, %d)",
  21. cl.r, cl.g, cl.b,
  22. ratio / (float)factor,
  23. cr.r, cr.g, cr.b,
  24. color.r, color.g, color.b
  25. );*/
  26. return color;
  27. }
  28. void Pattern::step(Color pixels[], int len, int64_t &last_us, Fixed &offset) const {
  29. int64_t now_us = time_us();
  30. int64_t duration_us = last_us == 0 ? 0 : now_us - last_us;
  31. last_us = now_us;
  32. //ESP_LOGI(TAG, "duration %d", duration_us);
  33. int offset_delta = (duration_us << shift) / (cycle_time_ms * 1000);
  34. if (reverse) offset -= offset_delta; else offset += offset_delta;
  35. Fixed off = march ?
  36. (((int)offset * cycle_length) & ~((1 << shift) - 1)) / cycle_length :
  37. offset;
  38. //ESP_LOGI(TAG, "cycle time %d, delta %d, offset %d, off %d", cycle_time_ms, offset_delta, offset, off);
  39. for (int i = 0; i < len; ++i) {
  40. pixels[i] = gradient.at(off + ((i << shift) / cycle_length));
  41. }
  42. }
  43. LEDStrip::LEDStrip(int _length) :
  44. length(_length), pattern(NULL),
  45. pixels(new Color[_length]),
  46. last_us(0), offset(0)
  47. {}
  48. void LEDStrip::step() {
  49. if (pattern) pattern->step(pixels, length, last_us, offset);
  50. }
  51. static std::string termcolor(Color c) {
  52. return "\x1b[48;2;" +
  53. std::to_string((int)c.r) + ";" +
  54. std::to_string((int)c.g) + ";" +
  55. std::to_string((int)c.b) + "m";
  56. }
  57. void TerminalLEDs::show() const {
  58. std::string line;
  59. for (int i = 0; i < length; i++) {
  60. line += termcolor(pixels[i]) + " ";
  61. }
  62. line += "\x1b[0m";
  63. ESP_LOGI(TAG, "%s", line.c_str());
  64. }