🛠 Publier et s'abonner en MQTT avec PubSubClient
Objectives
Connect the ESP8266-ESP-12E to an MQTT broker (the king protocol of home automation, very lightweight and perfectly suited for the chip) using the PubSubClient library. The module publishes its RSSI every 5 seconds on the topic "esp12e/rssi" and controls the onboard LED by subscribing to "esp12e/led" (ON/OFF messages). You will learn how to maintain the connection (keepalive via mqtt.loop called regularly), manual reconnection when the broker disappears, and how to use the reception callback. The broker can be Mosquitto on a Raspberry Pi or a NAS on the local network.
Hardware
- 1 ESP8266-ESP-12E module powered at 3.3 V (current ≥ 500 mA)
- 1 MQTT broker on the network (Mosquitto: sudo apt install mosquitto-clients for testing)
- Arduino library "PubSubClient" (Nick O'Leary) installed via the library manager
- 2.4 GHz Wi-Fi network
Complete code
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
const char* SSID = "mon-reseau";
const char* PASS = "mot-de-passe";
const char* BROKER = "192.168.1.50"; // IP du broker Mosquitto
const uint8_t LED = 2; // active-LOW
WiFiClient net;
PubSubClient mqtt(net);
unsigned long dernierePub = 0;
void callback(char* topic, byte* payload, unsigned int len) {
String msg = String((char*)payload).substring(0, len);
msg.toUpperCase;
if (String(topic) == "esp12e/led") {
digitalWrite(LED, msg == "ON" ? LOW : HIGH); // LOW = allumee
Serial.printf("LED -> %s\n", msg.c_str);
}
}
void connexion {
WiFi.mode(WIFI_STA);
WiFi.begin(SSID, PASS);
while (WiFi.status != WL_CONNECTED) { delay(250); Serial.print("."); yield; }
while (!mqtt.connected) {
Serial.print("Connexion MQTT...");
if (mqtt.connect("esp12e-01")) { // client id unique sur le broker
Serial.println(" ok");
mqtt.subscribe("esp12e/led");
} else {
Serial.printf("echec rc=%d, retry 2s\n", mqtt.state);
delay(2000);
}
}
}
void setup {
Serial.begin(115200);
pinMode(LED, OUTPUT);
mqtt.setServer(BROKER, 1883);
mqtt.setCallback(callback);
connexion;
}
void loop {
if (WiFi.status != WL_CONNECTED || !mqtt.connected) connexion;
mqtt.loop; // keepalive + réception, indispensable
if (millis - dernierePub > 5000) {
dernierePub = millis;
char buf[16];
snprintf(buf, sizeof(buf), "%d", WiFi.RSSI);
mqtt.publish("esp12e/rssi", buf);
}
delay(10);
}
Expected verification
Start the broker then the module: the console displays the Wi-Fi connection then "MQTT connection... ok". On the broker side, mosquitto_sub -t 'esp12e/#' should display an RSSI every 5 seconds. Send mosquitto_pub -t esp12e/led -m ON: the module's LED turns on immediately; "OFF" turns it off. Stop the broker: the module displays failures then reconnects on its own when the broker comes back.
Common errors
- Forgetting mqtt.loop in loop: without it, there is no keepalive (the broker disconnects after 15 s) and no messages are received.
- Using a delay of several seconds: the MQTT connection and the Wi-Fi stack saturate, use delay(10) or yield.
- Two modules with the same client id: the broker repeatedly kicks out the first one of the two ("ping timeout"), give a unique id to each device.
- Setting the broker's IP on another subnet or forgetting to open port 1883 in the server's firewall.
- Publishing before connecting: publish returns false as long as mqtt.connected is false, always check the state.
Other tutorials for this board
Code examples for this board
clignotante.inoArduinobouton-led.inoArduinorespiration.inoArduinodht11.inoArduinoluxmetre.inoArduinoserveur-web.inoArduino