Skip to content

Instantly share code, notes, and snippets.

@ChrisHinde
Last active August 27, 2016 16:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ChrisHinde/0b0e6eaf2efa42faa4d6757d973caf13 to your computer and use it in GitHub Desktop.
Save ChrisHinde/0b0e6eaf2efa42faa4d6757d973caf13 to your computer and use it in GitHub Desktop.
Functions to setup and control RGB LEDs/strips with Lua on NodeMCU
--[[ rgb_pwm.lua
Created by Christopher Hindefjord (ChrisHinde / chris@hindefjord.se)
CC-0 > No copyright claimed - You are free to use these snippets however, wherever, you like
These are support functions (and settings( set the PWM (Pulse Width Modulation) output to "control" standard RGB LEDs or Strips
This will not work if you have NeoPixel style LEDs (like WS2812), they requrie a different setup!
]]--
-- Configuration for the PWM/RGB output
-- If your RGB LED/strip is common anode (There's one positive lead and three negative [cathodes], which is common)
-- the values need to be inverted (So to turn on a color to max [e.g 1023], then the PWM output needs to be 0,
-- since the pin is pulled to ground and thus the LED is lit)
-- Change PWM_INV to false _and_ PWM_OFF to 0 if your RGB LED is common cathode
-- If your MCU uses 8 bit PWM instead of 10 bit, change PWM_MAX to 255
PWM_MAX = 1023
PWM_OFF = 1023
PWM_INV = true
-- The pins that are used for the RGB light
PIN_R = 1
PIN_G = 2
PIN_B = 3
-- PIN_W = 4 -- Uncomment this if your RGB LED/strip has a white component
-- Function to initiate the PWM output for RGB
-- If your RGB LED/strip has a white component, uncomment every fourth line in each section
function init_rgb()
pwm.setup(PIN_R, 500, PWM_OFF)
pwm.setup(PIN_G, 500, PWM_OFF)
pwm.setup(PIN_B, 500, PWM_OFF)
--pwm.setup(PIN_W, 500, PWM_OFF)
pwm.start(PIN_R)
pwm.start(PIN_G)
pwm.start(PIN_B)
--pwm.start(PIN_W)
end
-- Function to set the output RGB via PWM
-- If your RGB LED/strip has a white LED, uncomment every fourth line in each section
function set_rgb( rgb )
-- If we should "turn off" the light
if (rgb == "off") or (rgb == "0") or (rgb == {0,0,0}) or (rgb == {0,0,0,0}) then
pwm.setduty(PIN_R,PWM_OFF)
pwm.setduty(PIN_G,PWM_OFF)
pwm.setduty(PIN_B,PWM_OFF)
-- pwm.setduty(PIN_W,PWM_OFF)
return
end
-- Initiate "local" variables
r = rgb[1]
g = rgb[2]
b = rgb[3]
--w = rgb[4]
-- If needed, invert the values
if PWM_INV then
r = PWM_MAX - r
g = PWM_MAX - g
b = PWM_MAX - b
--w = PWM_MAX - w
end
-- Set the PWM output
pwm.setduty(PIN_R, r)
pwm.setduty(PIN_G, g)
pwm.setduty(PIN_B, b)
-- pwm.setduty(PIN_W, w)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment