Simple neopixel (WS2812) library, tuned for stm32 (L432) at 80 MHz Should be compatible with any stm32, different clock speed may require timing adjustments in neopixel.c
Dependents: Nucleo_neopixel_ovgu Nucleo_neopixel_ovgu1 Nucleo_neopixel_ovgu3
Fork of NeoPixel by
Diff: neopixel.cpp
- Revision:
- 1:037882a8e193
- Parent:
- 0:a81364d9a67b
--- a/neopixel.cpp Tue Mar 21 21:17:08 2017 +0000 +++ b/neopixel.cpp Mon Dec 11 12:54:00 2017 +0000 @@ -1,14 +1,15 @@ #include "mbed.h" #include "neopixel.h" -NeoPixelOut::NeoPixelOut(PinName pin) : DigitalOut(pin) +NeoPixel::NeoPixel(PinName pin, int n) : DigitalOut(pin) { - normalize = false; - global_scale = 1.0f; + _pixels = (Pixel*)malloc(n*sizeof(Pixel)); + memset(_pixels, 0, n*sizeof(Pixel)); + _npixels = n; } // The timing should be approximately 800ns/300ns, 300ns/800ns -void NeoPixelOut::byte(register uint32_t byte) +void NeoPixel::byte(register uint32_t byte) { for (int i = 0; i < 8; i++) { gpio_write(&gpio, 1); @@ -34,45 +35,20 @@ } -void NeoPixelOut::send(Pixel *colors, uint32_t count, bool flipwait) +void NeoPixel::show(void) { // Disable interrupts in the critical section __disable_irq(); - - Pixel* rgb; - float fr,fg,fb; - for (int i = 0; i < count; i++) { - rgb = colors++; - fr = (int)rgb->r; - fg = (int)rgb->g; - fb = (int)rgb->b; - - if (normalize) { - float scale = 255.0f/(fr+fg+fb); - fr *= scale; - fg *= scale; - fb *= scale; - } - - fr *= global_scale; - fg *= global_scale; - fb *= global_scale; - - if (fr > 255) fr = 255; - if (fg > 255) fg = 255; - if (fb > 255) fb = 255; - if (fr < 0) fr = 0; - if (fg < 0) fg = 0; - if (fb < 0) fb = 0; - + + for (int i = 0; i < _npixels; i++) { // Black magic to fix distorted timing #ifdef __HAL_FLASH_INSTRUCTION_CACHE_DISABLE __HAL_FLASH_INSTRUCTION_CACHE_DISABLE(); #endif - byte((int)fg); - byte((int)fr); - byte((int)fb); + byte((_pixels+i)->g); + byte((_pixels+i)->r); + byte((_pixels+i)->b); #ifdef __HAL_FLASH_INSTRUCTION_CACHE_ENABLE __HAL_FLASH_INSTRUCTION_CACHE_ENABLE(); @@ -80,12 +56,19 @@ } __enable_irq(); - - if (flipwait) flip(); + wait_us(50); } -void NeoPixelOut::flip(void) +void NeoPixel::setColor(int i, uint32_t color) { - wait_us(50); + if ((i>=0) && (i<_npixels)) + (_pixels+i)->hex = color; } + + +void NeoPixel::clear(void) +{ + for (int i=0; i<_npixels; i++) + (_pixels+i)->hex = 0; +} \ No newline at end of file