ESP32 MQTT

Author avatarSid | Last edit 10/02/2024 by Disisid

No image yet

Use the ESP32's wifi module to communicate with a computer
Difficulty
Easy
Duration
1 hour(s)
Categories
Electronics, Robotics
Cost
0 USD ($)
License : Attribution (CC BY)

Materials

Tools

Step 1 - Prepare an MQTT Broker

Before we begin, we need to ensure you have an MQTT broker to communicate and test with. We can download MQTTX to ensure communication.





Step 2 - Install ESP32 Development Board & other dependancies

Ensure that the ESP32 dev library is installed, then go to libraries in the Arduino IDE and download PubSubClient.




Step 3 - Full Code

Copy the full code into your IDE. Feel free to change things like the text it prints, etc


 1 #include <WiFi.h>
 2 #include <PubSubClient.h>
 3 
 4 // WiFi
 5 const char *ssid = "xxxxx"; // Enter your Wi-Fi name
 6 const char *password = "xxxxx";  // Enter Wi-Fi password
 7 
 8 // MQTT Broker
 9 const char *mqtt_broker = "broker.emqx.io";
10 const char *topic = "emqx/esp32";
11 const char *mqtt_username = "emqx";
12 const char *mqtt_password = "public";
13 const int mqtt_port = 1883;
14 
15 WiFiClient espClient;
16 PubSubClient client(espClient);
17 
18 void setup() {
19     // Set software serial baud to 115200;
20     Serial.begin(115200);
21     // Connecting to a WiFi network
22     WiFi.begin(ssid, password);
23     while (WiFi.status() != WL_CONNECTED) {
24         delay(500);
25         Serial.println("Connecting to WiFi..");
26     }
27     Serial.println("Connected to the Wi-Fi network");
28     //connecting to a mqtt broker
29     client.setServer(mqtt_broker, mqtt_port);
30     client.setCallback(callback);
31     while (!client.connected()) {
32         String client_id = "esp32-client-";
33         client_id += String(WiFi.macAddress());
34         Serial.printf("The client %s connects to the public MQTT broker\n", client_id.c_str());
35         if (client.connect(client_id.c_str(), mqtt_username, mqtt_password)) {
36             Serial.println("Public EMQX MQTT broker connected");
37         } else {
38             Serial.print("failed with state ");
39             Serial.print(client.state());
40             delay(2000);
41         }
42     }
43     // Publish and subscribe
44     client.publish(topic, "Hi, I'm ESP32 ^^");
45     client.subscribe(topic);
46 }
47 
48 void callback(char *topic, byte *payload, unsigned int length) {
49     Serial.print("Message arrived in topic: ");
50     Serial.println(topic);
51     Serial.print("Message:");
52     for (int i = 0; i < length; i++) {
53         Serial.print((char) payload[i]);
54     }
55     Serial.println();
56     Serial.println("-----------------------");
57 }
58 
59 void loop() {
60     client.loop();
61 }

Comments

Draft