I'm currently writing a code to drive an LED strip using PWM and MOSFETs (IRLZ34N).
I've chosen to go with UDP for the server (obvious choice, we don't need connections, acknowledged packets and what else - losing one packet won't be a big deal and probably won't happen).
One more thing as to why connections aren't needed: it's going to be controlled by an Android application I've put together which features a color wheel, so there will be plenty changes and being "one stop" off won't even be noticeable.
This application sends an UDP packet whenever the color is changed to the IP specified in the settings in the format "R,G,B" so for example "124,255,10" to represent this color.
The LUA code (untested, since my circuit is not complete yet and I need to resolder two pins on my ESP-07 - asking for review here!)
wifi.sta.config("redacted","redacted")
wifi.sta.connect()
-- Wait for the Connection
tmr.alarm(1,1000, 1, function()
if wifi.sta.getip()==nil then
print(" Wait to IP address!")
else
-- Connected to WiFi
print("New IP address is "..wifi.sta.getip())
tmr.stop(1)
-- pins of the RGB strip according to:
-- https://github.com/nodemcu/nodemcu-firmware/wiki/nodemcu_api_en#new_gpio_map
redPin = 4
greenPin = 6
bluePin = 5
-- PWM frequency - adjust if LED flickers or PWM doesn't look linear
pwmFreq = 250
-- set up pins as PWM pins
pwm.setup(redPin, pwmFreq, 0)
pwm.setup(greenPin, pwmFreq, 0)
pwm.setup(bluePin, pwmFreq, 0)
-- start PWM output on the pins (effectively no light yet)
pwm.start(redPin)
pwm.start(greenPin)
pwm.start(bluePin)
-- create UDP server to listen for our color changes
srv = net.createServer(net.UDP);
srv:on("receive",function(cu,msg)
-- we expect the packet in "R,G,B" format
-- thus use the split function from our functions file (similar to php explode, returning an array)
red, green, blue = msg:match("([^,]+),([^,]+),([^,]+)")
pwm.setDuty(redPin, red*4);
pwm.setDuty(greenPin, green*4);
pwm.setDuty(bluePin, blue*4);
end)
end
end)
I've chosen to use three separate values for each pin and it's colors since it's easier and doesn't make a difference lines-of-code wise (easiest readable loop over an array is three lines so I feel like my style is more concise than using an array, but it's an edge case).
I've used the "wait for WiFi connection" code I found in this board,