I was curious if that would work too
So I just tried with this code sending 1000 messages at 20Hz to my RPi on my local network (ESP32 connected through Wi-FI, RPi on the LAN via Ethernet at 10.0.0.23, MQTT server with no login/pwd).
#include <WiFi.h>
#include <PubSubClient.h>
const char* ssid = "***************";
const char* password = "***************";
const char* mqttTocic = "/something/to/test";
const size_t payloadSize = 20;
char mqttMessage[payloadSize];
IPAddress mqttServerIP(10, 0, 0, 23); // 10.0.0.23
WiFiClient wifiClient;
PubSubClient client(wifiClient);
void sendMqttMessage() {
if (client.connected()) {
if (client.connect("ESP32")) {
snprintf(mqttMessage, payloadSize, "%lu", millis());
client.publish(mqttTocic, mqttMessage, false); // false for not retained
} else {
Serial.print("MQTT Publish failed, rc=");
Serial.println(client.state());
}
}
}
void setup() {
Serial.begin(115200); Serial.println();
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
if (WiFi.waitForConnectResult() != WL_CONNECTED) {
Serial.println("WiFi Failed!");
while (true) yield();
}
Serial.println("WiFi OK!");
client.setServer(mqttServerIP, 1883);
if (!client.connected()) {
if (!client.connect("ESP32")) {
Serial.println("MQTT Server not reacheable!");
while (true) yield();
}
}
Serial.println("MQTT OK!");
Serial.println("press a key to start!");
while (Serial.read() == -1);
Serial.println("Sending messages!");
}
void loop() {
const unsigned long period = 50;
static unsigned long count = 0;
static unsigned long startTime = millis();
static unsigned long lastTime = startTime;
if (millis() - lastTime >= period) { // 10Hz
sendMqttMessage();
if (count++ >= 1000) {
unsigned long deltaT = millis() - startTime;
Serial.print("sent 1000 messages in ");
Serial.print(deltaT);
Serial.println(" ms");
while (true) yield();
}
lastTime += period;
}
}
on my RPi I ran the following command
mosquitto_sub -h localhost -t "/something/to/test"
Then once I typed enter in the Serial monitor (sending something like CR or CR/LF or LF) at 115200 bauds, I saw in the remote shell terminal the MQQT messages flowing in
22102
22152
22202
22252
22302
22352
22402
22452
22502
22552
22602
22652
22702
22752
22802
...
71952
72002
72052
72102
and the Arduino said:
WiFi OK!
MQTT OK!
press a key to start!
Sending messages!
sent 1000 messages in 50051 ms
I looked at the timing of the 1000 values in a spreadsheet, the millis values are all 50ms apart
so it seems you can handle 20Hz fine that way, it did not skip a beat.
if you want to test the code, you'll have to modify the Wi-Fi connexion info and the MQTT server IP address.
const char* ssid = "***************";
const char* password = "***************";
IPAddress mqttServerIP(10, 0, 0, 23); // 10.0.0.23
of course the notification of the MQTT server will possibly add some delay/latency