... | ... | @@ -336,6 +336,59 @@ void loop(){ |
|
|
|
|
|
```
|
|
|
|
|
|
Maybe you have to include ArdionoJson.h to your Library in wokwi.
|
|
|
|
|
|
Go to Library Manager-\> press the + button -\> type "ArduinoJson" and add it.
|
|
|
|
|
|
You will Probaly get an error Msg for the AsyncMqttClient library. Without the premium version of wokwi we have to include a similiar library.
|
|
|
|
|
|
Go to Library Manager-\> press the + button -\> type "PubSubClient" and add it.
|
|
|
|
|
|
Now that we use a different library we need some adjustments!
|
|
|
|
|
|
So we will review the code together:
|
|
|
|
|
|
1. WIFI and MQTT Setup
|
|
|
|
|
|
```
|
|
|
#include <WiFi.h> #include <PubSubClient.h>WiFiClient wifiClient; PubSubClient mqttClient(wifiClient);
|
|
|
```
|
|
|
|
|
|
```
|
|
|
void connectToWifi() { Serial.println("Connecting to Wi-Fi..."); WiFi.begin(WIFI_SSID, WIFI_PASSWORD); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(); Serial.print("Connected to Wi-Fi with IP: "); Serial.println(WiFi.localIP()); }void connectToMqtt() { while (!mqttClient.connected()) { Serial.println("Connecting to MQTT..."); if (mqttClient.connect(ID)) { Serial.println("Connected to MQTT"); } else { Serial.print("Failed to connect to MQTT, state: "); Serial.println(mqttClient.state()); delay(2000); } } }
|
|
|
```
|
|
|
|
|
|
```
|
|
|
void setup() { Serial.begin(115200);// Setup MQTT server mqttClient.setServer(MQTT_HOST, MQTT_PORT);// Connect to WiFi connectToWifi();// Connect to MQTT connectToMqtt(); }
|
|
|
```
|
|
|
|
|
|
```
|
|
|
void loop() {
|
|
|
// Ensure the client is connected
|
|
|
if (!mqttClient.connected()) {
|
|
|
connectToMqtt();
|
|
|
}
|
|
|
|
|
|
// Handle MQTT client loop
|
|
|
mqttClient.loop();
|
|
|
|
|
|
// Publish message every 1 second
|
|
|
unsigned long currentMillis = millis();
|
|
|
if (currentMillis - previousMillis >= interval) {
|
|
|
previousMillis = currentMillis;
|
|
|
publishMsgBasket();
|
|
|
}
|
|
|
}
|
|
|
```
|
|
|
|
|
|
```
|
|
|
void publishMsgBasket() {
|
|
|
String msg = set_fruitbasketMsg();
|
|
|
String topic = "MYfancyTopic/Dummy/Data/Basket";
|
|
|
mqttClient.publish(topic.c_str(), msg.c_str());
|
|
|
}
|
|
|
```
|
|
|
|
|
|
Now the ESP32 should send the data packet every 1000ms (1 second) to the MQTT broker via your router. To verify this, you can use sniffer tools to subscribe to the topic or even monitor the entire broker (i.e., all topics). Here, we will show you our favorite tool, which allows you to do many additional things.
|
|
|
|
|
|
### Verifying the MQTT Communication
|
... | ... | |