This project demonstrates how to use an ESP32 board as an MQTT client, allowing easy configuration via a web portal and providing access to key features through a serial CLI. This simplifies both wireless communication and device management.
- MQTT client functionality with ESP32
- Web-based configuration portal for network and MQTT settings
- Basic CLI over serial for easy command access
- Lightweight and customizable
- ESP32 development board
- USB cable
- Arduino IDE or PlatformIO
- ESP32 core installed in the Arduino IDE
- MQTT broker (e.g., Mosquitto)
- Libraries:
- PubSubClient (for MQTT)
- WiFiManager (https://github.com/tzapu/WiFiManager)
- Preferences (for saving settings)
To clone the repository, use the following command:
git clone https://github.com/MarcoGerladi/ESP32MqttExample.git
- Open Arduino IDE or PlatformIO.
- Install the necessary libraries:
- PubSubClient
- WiFiManager (https://github.com/tzapu/WiFiManager)
- Preferences
- Upload the code to your ESP32 board.
- Once the ESP32 is powered on, it will create a WiFi access point (AP).
- Connect to the AP using your phone or computer.
- Open a browser and navigate to the ESP32’s IP address (usually 192.168.4.1).
- Enter your WiFi network details and MQTT broker information.
- At this point the ESP32 will stop the configuration portal. in order to restart it, execute the
config_portal
command via theCLI
Use the serial monitor to access the CLI. Here are the available commands:
help
: Shows the list of the available commandscli_reset
: Reset the devicecli_mqtt_info
: Prints stored mqtt settingscli_mqtt_server
: Set MQTT broker IP addresscli_mqtt_port
: Set MQTT broker portcli_mqtt_user
: Set MQTT usernamecli_mqtt_password
: Set MQTT passwordcli_config_portal
: Enable Config Portal
The ESP32 automatically connects to the MQTT Broker. In case the connection is lost, the ESP32 will retry to connect to the broker each 5s.
/* --------------------- Try to reconnect to MQTT Broker -------------------- */
if ( millis() - timestamp > 5000) {
MQTT_reconnect();
timestamp = millis();
}
The ESP32 communicates with the MQTT broker by subscribing and publishing to specific topics.
- Publish exmaple:
Publish Topic: esp32/temperature
/* ---------------------------- Publish MQTT Data --------------------------- */
mqttClient.loop();
mqttClient.publish("esp32/temperature", "19°C");
-
Subscribe Example:
Subscribed Topic: esp32/output
mqttClient.subscribe("esp32/output");