markav2

04-FastLED with Arduino Tutorial Introduction - How to Code for RGB LED Strips (WS2812B)

Apr 8th, 2021 (edited)
170
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #from Dave's Garage YouTube video https://youtu.be/aub9PecrbuM
  2.  
  3. #include <Arduino.h>
  4. #include <U8g2lib.h>
  5. #define FASTLED_INTERNAL
  6. #include <FastLED.h>
  7.  
  8. #define OLED_CLOCK  15          // Pins for the OLED display
  9. #define OLED_DATA   4
  10. #define OLED_RESET  16
  11.  
  12. #define NUM_LEDS    20          // FastLED definitions
  13. #define LED_PIN     5
  14.  
  15. CRGB g_LEDs[NUM_LEDS] = {0};    // Frame buffer for FastLED
  16.  
  17. U8G2_SSD1306_128X64_NONAME_F_HW_I2C g_OLED(U8G2_R2, OLED_RESET, OLED_CLOCK, OLED_DATA);
  18. int g_lineHeight = 0;
  19.  
  20. // FramesPerSecond
  21. //
  22. // Tracks a weighted average to smooth out the values that it calcs as the simple reciprocal
  23. // of the amount of time taken specified by the caller.  So 1/3 of a second is 3 fps, and it
  24. // will take up to 10 frames or so to stabilize on that value.
  25.  
  26. double FramesPerSecond(double seconds)
  27. {
  28.   static double framesPerSecond;
  29.   framesPerSecond = (framesPerSecond * .9) + (1.0 / seconds * .1);
  30.   return framesPerSecond;
  31. }
  32.  
  33. void setup()
  34. {
  35.   pinMode(LED_BUILTIN, OUTPUT);
  36.   pinMode(LED_PIN, OUTPUT);
  37.  
  38.   Serial.begin(115200);
  39.   while (!Serial) { }
  40.   Serial.println("ESP32 Startup");
  41.  
  42.   g_OLED.begin();
  43.   g_OLED.clear();
  44.   g_OLED.setFont(u8g2_font_profont15_tf);
  45.   g_lineHeight = g_OLED.getFontAscent() - g_OLED.getFontDescent();        // Descent is a negative number so we add it to the total
  46.  
  47.   FastLED.addLeds<WS2812B, LED_PIN, GRB>(g_LEDs, NUM_LEDS);               // Add our LED strip to the FastLED library
  48.   FastLED.setBrightness(4);
  49. }
  50.  
  51. void loop()
  52. {
  53.   bool bLED = 0;
  54.   double fps = 0;
  55.  
  56.   uint8_t initialHue = 0;
  57.   const uint8_t deltaHue = 16;
  58.   const uint8_t hueDensity = 4;
  59.  
  60.   for (;;)
  61.   {
  62.     bLED = !bLED;                                                         // Blink the LED off and on  
  63.     digitalWrite(LED_BUILTIN, bLED);
  64.  
  65.     double dStart = millis() / 1000.0;                                    // Display a frame and calc how long it takes
  66.  
  67.     // Handle OLED drawing
  68.  
  69.     g_OLED.clearBuffer();
  70.     g_OLED.setCursor(0, g_lineHeight);
  71.     g_OLED.printf("FPS: %.1lf", fps);
  72.     g_OLED.sendBuffer();
  73.  
  74.     // Handle LEDs
  75.  
  76.     fill_rainbow(g_LEDs, NUM_LEDS, initialHue += hueDensity, deltaHue);
  77.  
  78.     FastLED.show();
  79.  
  80.     double dEnd = millis() / 1000.0;
  81.     fps = FramesPerSecond(dEnd - dStart);
  82.   }
  83. }
RAW Paste Data