MQTT Broker(Mosquitto) - ESP32
--Resource
--
1. ESP8266 code
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
const char* ssid = "YourNetworkName";
const char* password = "YourNetworkPassword";
const char* mqttServer = "m11.cloudmqtt.com";
const int mqttPort = 12948;
const char* mqttUser = "YourMqttUser";
const char* mqttPassword = "YourMqttUserPassword";
WiFiClient espClient;
PubSubClient client(espClient);
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.println("Connecting to WiFi..");
}
Serial.println("Connected to the WiFi network");
client.setServer(mqttServer, mqttPort);
client.setCallback(callback);
while (!client.connected()) {
Serial.println("Connecting to MQTT...");
if (client.connect("ESP8266Client", mqttUser, mqttPassword )) {
Serial.println("connected");
} else {
Serial.print("failed with state ");
Serial.print(client.state());
delay(2000);
}
}
client.publish("esp/test", "Hello from ESP8266");
client.subscribe("esp/test");
}
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived in topic: ");
Serial.println(topic);
Serial.print("Message:");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
Serial.println("-----------------------");
}
void loop() {
client.loop();
}
2. ESP32 code
#include <WiFi.h>
#include <PubSubClient.h>
const char* ssid = "wifi ssid";
const char* password = "wifi password";
const char* mqttServer = "192.168.1.4"; // local ip address
const int mqttPort = 1883;
const char* mqttUser = "mqqtt_user that configured on mosquitto";
const char* mqttPassword = "mqqtt_password for mqtt_user that configured on mosquitto";
WiFiClient espClient;
PubSubClient client(espClient);
void setup() {
WiFi.mode(WIFI_STA);
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.println("Connecting to WiFi..");
}
Serial.println("Connected to the WiFi network");
client.setServer(mqttServer, mqttPort);
while (!client.connected()) {
Serial.println("Connecting to MQTT...");
if (client.connect("arduinoClient",mqttUser,mqttPassword)) {
Serial.println("connected");
} else {
Serial.print("failed with state ");
Serial.print(client.state());
delay(2000);
}
}
client.publish("esp/test", "Hello from ESP32");
}
void loop() {
client.publish("esp/test", "Hello from ESP32");
delay(5000);
client.loop();
}