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)
    else
      gpio.write(4, gpio.LOW)
    end
  end
  if data ~= nil then
    print(topic .. ":" .. data)
  else
    print(topic .. " without data")
  end
end)

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

-- 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())
        dofile(script);
    else
        if x > 0 then
            -- Keep trying
            tmr.alarm(0, 1000, 0, function() ConnStatus(script, x - 1) end)
        else
            print("Connection failed")
        end
    end
end

-- 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 192.168.1.1 -t "nodemcu/led" -m "1"
mosquitto_pub -h 192.168.1.1 -t "nodemcu/led" -m "0"

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

Leave a Reply

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