MQTT client on ESP32 PLCs over Wi-Fi
MQTT client on ESP32 PLCs over Wi-Fi
The code of the previous lesson adapts to any ESP32 PLC to use MQTT over Wi-Fi. Replace every use of the Ethernet object with the Wi-Fi one:
#include <WiFi.h>
#include <PubSubClient.h>
const char* ssid = "yourSSID";
const char* password = "yourPASSWORD";
const char* mqtt_server = "10.42.0.1";
WiFiClient espClient;
PubSubClient client(espClient);
void setup_wifi() {
delay(10);
// Start by connecting to a Wi-Fi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println();
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void setup() {
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}The callback, the reconnect() function and the loop() are the same as in the Ethernet lesson, including the user and password in client.connect().
The performance is the same as with the Ethernet port, and the choice depends on the environment. Ethernet is the better option for fixed installations because it is more stable and immune to radio interference; Wi-Fi is useful when cabling is difficult or for commissioning. Keep the Wi-Fi network of the machines separate from the corporate network, use WPA2 or WPA3, and do not leave the Wi-Fi password in code that you share.
See the ESP32 PLC range at www.industrialshields.com.
There are no comments for now.