ESP32 Ethernet W5500 MQTT
Arduino-based project that uses ESP32 and W5500 Ethernet modules to connect to an MQTT broker and post messages periodically.
Project Description
Arduino-based project that uses ESP32 and W5500 Ethernet modules to connect to an MQTT broker and post messages periodically.
- Include libraries :
- <SPI.h> : Library for SPI communication.
- <Ethernet.h> : Library for Ethernet connectivity.
- <PubSubClient.h> : Library for MQTT communication.
- Define constants and variables :
- ETHERNET_MAC : MAC address of the Ethernet module.
- ETHERNET_IP : IP address to be used when connected via Ethernet.
- ETHERNET_RESET_PIN, ETHERNET_CS_PIN : Pin numbers for Ethernet module-related pins.
- MQTT_HOSTNAME, MQTT_PORT : MQTT broker host and port.
- MQTT_PUBLISH_INTERVAL_MS : Interval for periodically publishing messages via MQTT (1 second).
- Ethernet and MQTT client setup :
- ethernetWizReset() : Resets the Ethernet module.
- macCharArrayToBytes() : Converts a MAC address from a string to a byte array.
- connectEthernet() : Configures and initializes the Ethernet connection.
- setupMqtt() : Sets up and initializes the MQTT client.
- connectToMqtt() : Connects to the MQTT broker and sets Last Will and Testament (LWT) properties.
- setup() :
- Serial communication is started.
- Ethernet connection is configured.
- MQTT client is configured and connected.
- loop() :
- If the MQTT client is not connected, it attempts to reconnect and waits until the connection is successful.
- Handles MQTT client's loop processing.
- Publishes the device's uptime to the "mydevice/uptime" topic at intervals defined by MQTT_PUBLISH_INTERVAL_MS.
This example demonstrates how to establish communication with an MQTT broker using an ESP32 and Ethernet module. It periodically publishes the device's uptime to the "mydevice/uptime" topic, making it a simple example for IoT device communication.