W5500を使ってESP32でEthernet MQTT通信する
Let's try MQTT communication with ESP32 ( Arduino core for the ESP32) using WIZnet's W5500 .
Software Apps and online services
1. Prepare
Perform up to 3 with reference to past articles .
- 1. Prepare
- 2. Connection
- 3. Library modification
2. Install MQTT library
Install the following libraries for MQTT communication.
The library can be searched by name from the library manager of the Arduino IDE and installed.
API documentation is available for PubSubClient .
3. Code
Write the following code to ESP32.
Change the MAC address according to your environment. DHCP is used to set the IP address , but you can also set a fixed IP by specifying the IP address or gateway as an argument to Ethernet .begin() .
Default values are set for dns , gateway , and subnet when setting with a fixed IP, so it may work only with the MAC address and IP address , but if you do not specify it, it will not work or communication will be unstable. So it is better to specify everything even if it is troublesome. You can check the details of Ethernet .begin() from the official reference below.
Also, the server address is the address of the MQTT Broker, and the MQTT Broker is required to check the operation. The easiest and recommended way to build MQTT Broker is to install mosqitto on Raspberry Pi .
4. Run
After confirming that the MQTT Broker is working, check the log on the serial monitor connected to the ESP32. If everything works fine, you should see something like this:
When you install mosquitto, PubSub client is installed in addition to Broker, so let's check the operation by launching terminals for Publish (Pub) and Subscribe (Sub).
Subscribe to topic output. When the ESP32 starts up, you can see ready being sent. If you miss it, reset the ESP32 and it will be sent again.
If you send a message (payload) to the input topic, you can check the reception on the serial monitor.
5. Summary
I tried MQTT communication using Ethernet with ESP32 . Since the ESP32 is equipped with WiFi , wireless communication can be tried more easily, but Ethernet has overwhelming communication stability that cannot be obtained with wireless, so I think it would be better to use it according to the application. .