Now that I have shown you two different hardware setups for the RGB strips, it is time to talk about the chip firmware and software.
I have chosen to use NodeMCU which uses Lua as the programming language. The good news is that all the functions you need are already there. As a result, even someone like me who doesn’t know Lua can easily write it.
And, thanks to a number of online blogs detailing what is going on, it is mostly copypasting existing code. Mostly this is adapted from the blog of openhardware.co.za. There were a few things unclear, but I suggest looking at it as he has much more verbose documentation.
For the most part, what is going on (at least on the surface) is fairly self explanatory, so I am just going to talk about how it takes the MQTT stuff and knows what to do with it. When the device gets a message this line in the code is triggered.
There are two vars returned, topic and data. In MQTT the topic works a lot like a folder structure in HTML, only instead of asking for the data in the specified folder1 you get a message with the data telling you what “folder” it is in.
In order to parse this message, I first check to be sure the data is valid. Because the data is being sent as text, I use tonumber() to get an int2 value from the data. In addition, the int needs to be in a certain range in order to work.3 Thus, the data check looks like this:
After this, it is just sorting out which “folder” the data is in so that we know which pin to change. If the message is, for example, telling it to change the red LED then the topic will be /home/Living/esp01/RED if you are using the preset values in the script.
3 The max value I can send to the PWM pin is 1023 because of how I used !! pwm.setup() and I am multiplying it by 10 because I have openHAB sending it a value from 0 to 100. As a result, my range of valid int values is 0 to 102. It is convoluted, but I didn’t want to delve into pwm.setup() and this works.