From 1ef1843e7ae5aadc21621b1a052471974b7b6ae1 Mon Sep 17 00:00:00 2001 From: Florian Klink Date: Fri, 27 Feb 2015 07:55:40 +0100 Subject: [PATCH] ws2812: change colors to accept RGB values Nobody would expect GRB input, and converting from RGB to GRB via Lua is too slow, so convert it in place before sending to the hardware. --- app/modules/ws2812.c | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/app/modules/ws2812.c b/app/modules/ws2812.c index aab28e92..337d32cd 100644 --- a/app/modules/ws2812.c +++ b/app/modules/ws2812.c @@ -36,28 +36,35 @@ static void ICACHE_FLASH_ATTR send_ws_1(uint8_t gpio) { } // Lua: ws2812.write(pin, "string") -// Byte triples in the string are interpreted as G R B values. -// ws2812.write(4, string.char(0, 255, 0)) uses GPIO2 and sets the first LED red. +// Byte triples in the string are interpreted as R G B values +// and sent to the hardware as G R B. +// ws2812.write(4, string.char(255, 0, 0)) uses GPIO2 and sets the first LED red. // ws2812.write(3, string.char(0, 0, 255):rep(10)) uses GPIO0 and sets ten LEDs blue. -// ws2812.write(4, string.char(255, 0, 0, 255, 255, 255)) first LED green, second LED white. +// ws2812.write(4, string.char(0, 255, 0, 255, 255, 255)) first LED green, second LED white. static int ICACHE_FLASH_ATTR ws2812_write(lua_State* L) { const uint8_t pin = luaL_checkinteger(L, 1); size_t length; const char *buffer = luaL_checklstring(L, 2, &length); + //ignore incomplete Byte triples at the end of buffer + length -= length % 3; + platform_gpio_mode(pin, PLATFORM_GPIO_OUTPUT, PLATFORM_GPIO_FLOAT); platform_gpio_write(pin, 0); os_delay_us(10); os_intr_lock(); const char * const end = buffer + length; - while (buffer != end) { + + size_t i = 1; + while (buffer + i <= end) { + uint8_t mask = 0x80; while (mask) { - (*buffer & mask) ? send_ws_1(pin_num[pin]) : send_ws_0(pin_num[pin]); + (buffer[i] & mask) ? send_ws_1(pin_num[pin]) : send_ws_0(pin_num[pin]); mask >>= 1; } - ++buffer; + i += ((i % 3) == 1) ? -1 : 2; } os_intr_unlock();