Controlling NodeMCU’s LED through MQTT

In this very simple example, I will setup a NodeMCU to connect to my MQTT broker and light its LED depending on received messages. This gives a very simple IOT device to test the MQTT protocol.

Disclaimer: As this is my first MQTT test, please note that all QoS and clientId stuffs are not well handled. I found that the blog posts from HiveMQ were very useful to understand the protocol and best practices.

The code is pretty simple since NodeMCU already includes an MQTT client module (make sure your firmware is compiled with MQTT support).

-- Init LED GPIO
gpio.mode(4, gpio.OUTPUT)
gpio.write(4, gpio.LOW)
-- Init MQTT client
m = mqtt.Client("nodemcu", 0, "admin", "admin")
m:on("offline", function(client) print ("offline") end)

-- On publish message receive event
m:on("message", function(client, topic, data) 
  if topic == "nodemcu/led" then
    if data == "0" then
      gpio.write(4, gpio.HIGH)
      gpio.write(4, gpio.LOW)
  if data ~= nil then
    print(topic .. ":" .. data)
    print(topic .. " without data")

-- Connect to MQTT broker
m:connect("", 1883, 0, 
    client:subscribe("nodemcu/led", 0, function(client) print("subscribe success") end)
  function(client, reason) 
    print("failed reason: "..reason)

-- Never exit
-- m:close();

Save this code as mqtt.lua and launch it once connected to the wifi. Optionally, I provide below my init.lua file that waits for wifi to be connected and then launches the MQTT script.

-- Test if wifi is connected then launch script
function ConnStatus(script, x)
    print("Waiting for IP ...")
    status = wifi.sta.status()
    if (status == 5) then
        print('Connected as '..wifi.sta.getip())
        if x > 0 then
            -- Keep trying
            tmr.alarm(0, 1000, 0, function() ConnStatus(script, x - 1) end)
            print("Connection failed")

-- Wait wifi to connect for 60 seconds
ConnStatus("mqtt.lua", 60)

To test your new IOT device, use the following commands from the console:

mosquitto_pub -h -t "nodemcu/led" -m "1"
mosquitto_pub -h -t "nodemcu/led" -m "0"

3 Replies to “Controlling NodeMCU’s LED through MQTT”

  1. I’m amazed, I have to admit. Rarely do I come across a blog
    that’s both educative and amusing, and without a doubt,
    you have hit the nail on the head. The problem is an issue that
    too few people are speaking intelligently about. Now i’m very happy I came across this during my search for
    something concerning this.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.