WS2812B Liblary this use SPI

WS2812B.cpp

Committer:
Suzutomo
Date:
2019-07-17
Revision:
5:62b6ac21c199
Parent:
4:02e88df0ae2d
Child:
6:21a721b31a20

File content as of revision 5:62b6ac21c199:

//--------------------------------------------------------
//  SPI を使って WS2812B を点灯するためのクラス
//      サポートするボード: Nucleo-F401RE, Nucleo-F446RE
//
//  2016/11/21, Copyright (c) 2016 MIKAMI, Naoki
//--------------------------------------------------------

#include "WS2812B.h"
#include "PeripheralPins.h"     // for pinmap_peripheral()

WS2812B::WS2812B(PinName pin, int num, bool inv)
    : spi_(pin, NC, NC),
      mySpi_((SPI_TypeDef *)pinmap_peripheral(pin, PinMap_SPI_MOSI))
{
    spi_.format(8, 0);
#if defined(STM32F446xx)
    spi_.frequency(22500000);
#else
#error This code is not move this board.
#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;
}

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,double brightness)
{
    for (int i = 0; i < bufferSize; i++) colors[i] = BrightAdjust(x,brightness);
}

void WS2812B::Send()
{
    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);
        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;
    __disable_irq();
    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();
    __enable_irq();
    free(colors_m);
}

void WS2812B::Clear(int k)
{
    for (int n=0; n<k; n++) colors[n] = 0;
    Send();
    Reset();
}

void WS2812B::Send3Bytes(uint16_t x0, uint16_t x1, uint16_t x2)
{
    SendByte(x0);
    SendByte(x1);
    SendByte(x2);
}

void WS2812B::SendByteNorm(uint8_t x)
{
    while ((mySpi_->SR & SPI_SR_TXE) != SPI_SR_TXE) {}
    mySpi_->DR = x;
}

void WS2812B::SendByteInv(uint8_t x)
{
    while ((mySpi_->SR & SPI_SR_TXE) != SPI_SR_TXE) {}
    mySpi_->DR = ~x;
}

void WS2812B::Brightness(double brightness)
{
    bright = brightness;
}