Important changes to repositories hosted on mbed.com
Mbed hosted mercurial repositories are deprecated and are due to be permanently deleted in July 2026.
To keep a copy of this software download the repository Zip archive or clone locally using Mercurial.
It is also possible to export all your personal repositories from the account settings page.
Diff: WS281X.cpp
- Revision:
- 32:64c391617f6c
- Parent:
- 29:a362df191524
- Child:
- 34:5a141ed5d52a
--- a/WS281X.cpp	Tue Sep 13 12:04:51 2016 +0000
+++ b/WS281X.cpp	Thu Oct 13 23:51:20 2016 +0000
@@ -26,6 +26,8 @@
 #include "pinmap.h"
 #endif
 
+#define USE_MALLOC          1   // 0:new, 1:malloc
+
 // TARGET_STM32F7
 // TARGET_DISCO_F746NG
 // TARGET_NUCLEO_F746ZG
@@ -58,7 +60,7 @@
 
 //----------------------------------------------------------------------------
 WS281X::WS281X(PinName wirePin, PinMode pinMode, int maxPixels, RGBOrder order)
-    : _wirePin(wirePin), _gpio(), _buf_owner(false)
+    : _wirePin(wirePin), _gpio(), _owned_buffer(false)
 {
     gpio_init_inout(&_gpio, wirePin, PIN_OUTPUT, pinMode, 0);
 #if defined(TARGET_STM)
@@ -72,7 +74,7 @@
 
 WS281X::WS281X(PinName wirePin, PinMode pinMode,
         RGBColor *buffer, int maxPixels, RGBOrder order)
-    : _wirePin(wirePin), _gpio(), _buf_owner(false)
+    : _wirePin(wirePin), _gpio(), _owned_buffer(false)
 {
     gpio_init_inout(&_gpio, wirePin, PIN_OUTPUT, pinMode, 0);
 #if defined(TARGET_STM)
@@ -86,23 +88,35 @@
 
 WS281X::~WS281X()
 {
-    if (_buf_owner && _pixels)
-        delete[] _pixels;
+    setPixelBuffer(0, 0);
 }
 
 void WS281X::setPixelBuffer(RGBColor *buffer, int maxPixels)
 {
-    if (_buf_owner && _pixels)
+    if (_owned_buffer && _pixels)
+    {
+#if USE_MALLOC
+        free(_pixels);
+#else
         delete[] _pixels;
+#endif
+    }
+    _owned_buffer = false;
+    _maxPixels = (maxPixels < 0) ? 0 : (maxPixels > MAX_PIXELS) ? MAX_PIXELS : maxPixels;
+    _pixels = (!_maxPixels) ? NULL : buffer;
 
-    _buf_owner = false;
-    _pixels = buffer;
-
-    _maxPixels = (maxPixels < 0) ? 0 : (maxPixels > MAX_PIXELS) ? MAX_PIXELS : maxPixels;
     if (!_pixels && _maxPixels > 0)
     {
+#if USE_MALLOC
+        _pixels = static_cast<RGBColor*>(malloc(sizeof(RGBColor)*_maxPixels));
+        if (_pixels)
+            _owned_buffer = true;
+        else
+            _maxPixels = 0;
+#else
         _pixels = new RGBColor[_maxPixels];
-        _buf_owner = true;   
+        _owned_buffer = true;   
+#endif
     }
     _numPixels = _maxPixels;
     clear();