nodemcu-firmware/docs/en/modules/ws2812.md

3.3 KiB

WS2812 Module

Since Origin / Contributor Maintainer Source
2015-02-05 Till Klocke, Thomas Soëte Till Klocke ws2812.c

ws2812 is a library to handle ws2812-like led strips. It works at least on WS2812, WS2812b, APA104, SK6812 (RGB or RGBW).

The library uses UART1 routed on GPIO2 (Pin D4 on NodeMCU DEVKIT) to generate the bitstream.

ws2812.init()

Initialize UART1 and GPIO2, should be called once and before write()

Parameters

none

Returns

nil

ws2812.write()

Send data to a led strip using its native format which is generally Green,Red,Blue for RGB strips and Green,Red,Blue,White for RGBW strips.

Syntax

ws2812.write(string)

Parameters

  • string payload to be sent to one or more WS2812 like leds.

Returns

nil

Example

ws2812.init()
ws2812.write(string.char(255,0,0,255,0,0) -- turn the two first RGB leds to green
ws2812.init()
ws2812.write(string.char(0,0,0,255,0,0,0,255) -- turn the two first RGBW leds to white

Buffer module

For more advanced animations, it is useful to keep a "framebuffer" of the strip, interact with it and flush it to the strip.

For this purpose, the ws2812 library offers a read/write buffer.

Example

Led chaser with a RGBW strip

local i, b = 0, ws2812.newBuffer(300, 4); b:fill(0,0,0,0); tmr.alarm(0, 50, 1, function()
        i=i+1
        b:fade(2)
        b:set(i%b:size()+1, 0, 0, 0, 255)
        b:write()
end)

ws2812.newBuffer()

Allocate a new memory buffer to store led values.

Syntax

ws2812.newBuffer(numberOfLeds, bytesPerLed)

Parameters

  • numberOfLeds length of the led strip
  • bytesPerLed 3 for RGB strips and 4 for RGBW strips

Returns

ws2812.buffer

ws2812.buffer:get()

Return the value at the given position

Syntax

buffer:get(index)

Parameters

  • index position in the buffer (1 for first led)

Returns

(color)

Example

buffer:get(2) -- return the color of the second led

ws2812.buffer:set()

Set the value at the given position

Syntax

buffer:set(index, color)

Parameters

  • index position in the buffer (1 for the first led)
  • color bytes of the color

Returns

nil

Example

buffer:set(1, 255, 0, 0) -- set the first led green for a RGB strip

ws2812.buffer:size()

Return the size of the buffer in number of leds

Syntax

buffer:size()

Parameters

none

Returns

int

ws2812.buffer:fill()

Fill the buffer with the given color. The number of given bytes must match the number of bytesPerLed of the buffer

Syntax

buffer:fill(color)

Parameters

  • color bytes of the color

Returns

nil

Example

buffer:fill(0, 0, 0) -- fill the buffer with black for a RGB strip

ws2812.buffer:fade()

Divide each byte of each led by the given value. Useful for a fading effect

Syntax

buffer:fade(value)

Parameters

  • value value by which divide each byte

Returns

nil

Example

buffer:fade(2)

ws2812.buffer:write()

Output the buffer to the led strip

Syntax

buffer:write()

Parameters

none

Returns

nil