WS2812B Liblary this use SPI

Revision:
3:c0a82b9775e6
Parent:
1:c7bb475f0022
Child:
4:02e88df0ae2d
--- a/WS2812B.cpp	Sat Jun 29 02:41:50 2019 +0000
+++ b/WS2812B.cpp	Sun Jun 30 08:26:25 2019 +0000
@@ -8,7 +8,7 @@
 #include "WS2812B.h"
 #include "PeripheralPins.h"     // for pinmap_peripheral()
 
-WS2812B::WS2812B(PinName pin, bool inv)
+WS2812B::WS2812B(PinName pin, int num, bool inv)
     : spi_(pin, NC, NC),
       mySpi_((SPI_TypeDef *)pinmap_peripheral(pin, PinMap_SPI_MOSI))
 {
@@ -25,27 +25,62 @@
 #endif
     if (!inv) fp = &WS2812B::SendByteNorm;
     else      fp = &WS2812B::SendByteInv;
+
+    colors = (uint32_t *)calloc(num,sizeof(uint32_t));
+    if (colors == NULL) printf("can not reserve memory\n");
+    bufferSize = num;
+    bright = 1.0;
+    //printf("buffer : %d\r\n",bufferSize);
+}
+
+uint32_t BrightAdjust(uint32_t x,double brightness)
+{
+    uint8_t r = ((x >> 16) & 0xFF) * brightness;
+    uint8_t g = ((x >> 8) & 0xFF) * brightness;
+    uint8_t b = ((x >> 0) & 0xFF) * brightness;
+    x = (r << 16) | (g << 8) | b;
+    return x;
+}
+
+void WS2812B::Write(int index,uint32_t x,double brightness)
+{
+    if (index >= 0 && index < bufferSize) colors[index] = BrightAdjust(x,brightness);
 }
 
-void WS2812B::Write(uint32_t x)
+void WS2812B::Write(uint32_t x,double brightness)
 {
-    static const uint32_t bit23 = 0x800000;
-    for (int n=0; n<24; n++)
-    {
-        if ((x & bit23) == bit23) T1HL();
-        else                      T0HL();
-        x <<= 1;
-    }
+    for (int i = 0; i < bufferSize; i++) colors[i] = BrightAdjust(x,brightness);
 }
 
-void WS2812B::Write(uint32_t x, int k)
+void WS2812B::Send()
 {
-    for (int n=0; n<k; n++) Write(x);
-}  
+    uint32_t *colors_m;
+    colors_m = (uint32_t *)calloc(bufferSize,sizeof(uint32_t));
+    for (int i = 0; i < bufferSize; i++) {
+        uint32_t x = colors[i];
+        x = BrightAdjust(x,bright);
+        //printf("%6x\r\n",x);
+        colors_m[i] = 0;
+        colors_m[i] |= ((x >> 8) & 0xFF00);
+        colors_m[i] |= ((x << 8) & 0xFF0000);
+        colors_m[i] |= (x & 0xFF);
+    }
+    static const uint32_t bit23 = 0x800000;
+    for (int i = 0; i < bufferSize; i++) {
+        for (int n=0; n<24; n++) {
+            if ((colors_m[i] & bit23) == bit23) T1HL();
+            else                      T0HL();
+            colors_m[i] <<= 1;
+        }
+    }
+    Reset();
+    free(colors_m);
+}
 
 void WS2812B::Clear(int k)
 {
-    for (int n=0; n<k; n++) Write(0x000000);
+    for (int n=0; n<k; n++) colors[n] = 0;
+    Send();
     Reset();
 }
 
@@ -68,3 +103,8 @@
     mySpi_->DR = ~x;
 }
 
+void WS2812B::Brightness(double brightness)
+{
+    bright = brightness;
+}
+