Use NodeMcu LUA ESP8266 send message to MQTT BROKER


Use NodeMcu LUA ESP8266 send message to MQTT BROKER



MQTT is a very popular IOT protocol which allows different devices to communicate through internet. The bridge between devices is called MQTT broker. devices can subscribe (get )message from broker , or publish (send) message to MQTT broker in a very simple way.

In this project, we will use NodeMcu(a ESP8266 wifi module) to publish message to a free MQTT broker (, then use web browser to subscribe the NodeMcu message from the broker.

Step 1. Install Arduino IDE for ESP8266

Please read the article : How to use Arduino IDE to program ESP8266 Wifi Module

Step 2. Install pubsubclient library

Download pubsubclient library from KOOKYE pubsubclient library

Unzip the file, then move the pubsubclient file to Arduino IDE libraries subfolder。

Step 3)config wifi hotspot and MQTT topic

Open arduino IDE–>File–>Examples–>pubsubclient–>mqtt_esp8266,you should made some changes as following:
A)In this project, our NodeMcu works in Wifi client mode, so you need tell the program your wifi hotspot name(ssid) and password.
In line 31 and 32, write the wifi ssid and password of your router or hotspot.

B)Change the topic of MQTT message, this step is optional( If you don’t want change topic, skip this step)
In line 95 and 130, you can change the topic of MQTT message. In this project, we changed the topic to “8266_MQTT_Pub”

Step 4)Burn the firmware:
Push FLASH button in NodeMCU , then Push RESET button. Hold both button for one or two seconds and release them at the same time. Now the NodeMCU enters into burning mode.

Now back to Arduino IDE ->Tools->board , select NodeMCU as your board (see following picture). Now you can upload code to your NodeMCU.

Click button in IDE top menu, the software will be burned into NodeMCU board.

Open Arduino Serial terminal(in upper right corner of IDE),you will see NodeMCU wifi connection status and MQTT message publishing status. See following picture:

Step 5) Subscribe the message you sent from NodeMCU

Open your browser and type , you will see a page which allows you to subscribe your topic(in our case, topic should be set to “8266_MQTT_Pub”),in the webpage Last message section, it will show your last message sent from NodeMCU is “Hellow World #20”, your will see “Hellow World #20” message in web page as following pictures:

Example, our last message from NodeMcu is “hello world #20” as following:

About the Author

amber administrator

You must be logged in to post a comment