Introduction
MQTT is a lightweight messaging protocol for small sensors and mobile devices. Node-RED is a flow-based tool for visual programming for the Internet of Things.
Prerequisites
- Mosquitto MQTT Broker (installed on PC/Pi)
- Node-RED (installed on PC/Pi)
- PubSubClient library for Arduino
ESP32 MQTT Code
#include <WiFi.h>
#include <PubSubClient.h>
const char* ssid = "YOUR_SSID";
const char* password = "YOUR_PASSWORD";
const char* mqtt_server = "192.168.1.XX"; // Your Broker IP
WiFiClient espClient;
PubSubClient client(espClient);
void setup() {
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
}
void loop() {
if (!client.connected()) reconnect();
client.loop();
// Publish every 5 seconds
static unsigned long last = 0;
if (millis() - last > 5000) {
last = millis();
client.publish("room/temp", "24.5");
}
}Node-RED Setup
- Drag an mqtt in node (Topic: room/temp).
- Drag a gauge node from the dashboard palette.
- Connect them and click Deploy.