Modbus RTU With ESP32-P4

Espressif has released the ESP32-P4, a new powerful dual-core RISC processor with a clock speed of 400 MHz.
In this tutorial, I will show you how to connect to Modbus RTU using a Waveshare ESP32-P4 high-performance development board.
Supplies


For this tutorial, I chose the ESP32-P4 high-performance development board from Waveshare because this development board was designed in the form factor of the well-known Raspberry Pi. This means that existing HATs for the Raspberry Pi can also be used with the ESP32-P4. An RS485 interface is required for a MODBUS RTU connection, which in this example is provided by an RS422/RS485 HAT for the Raspberry Pi from Zihatec.
Jumper Settings

The RS485 HAT can be jumpered to various UARTs on the Raspberry Pi. The ESP32-P4 also has 5 UARTS that can be routed to various GPIOs as desired.
On the ESP32-P4 board from Waveshare, the UART0 of the ESP32-P4 is connected to pins 8 and 10 of the expansion header (on the Raspberry Pi GPIO14 and 15 - UART0). At the same time, however, these pins are also connected to the UART-USB bridge for programming and debugging on the board, so that these pins cannot be used. Instead, we can use the alternative pins for the other UARTs of the Raspberry Pi.
We can now set two jumpers at U3, U4, or U5 (the corresponding line for pin routing must then be enabled in the software—see below).
We do not need the additional jumpers for the automatic transmit/receive switch RE0/3.
DIP Switch Setting
The HAT can be set to different configurations using 3 DIP switches. We are using the following settings for our experiment:
S1: OFF - ON - ON - OFF
S2: OFF - OFF - ON - ON
S3: ON - OFF - ON - ON
MODBUS Setup

For our experiment, we naturally need another MODBUS device with which we can communicate. For this test, I used a MODBUS relay box, also from Waveshare.
The connections A and B on the HAT are simply connected to the connections A and B on the other device.
Software

First, the correct board “ESP32-P4 Dev Module” must be selected in the Arduino IDE under ESP32.
In the test program, lines 60 to 62, the corresponding line for initializing the UART must now be enabled in accordance with the jumper settings:
The test program uses the RS485 library and MODBUS library from Vishnu Mohanan (CIRCUITSTATE Electronics LLP).
The program switches the relays of the connected relay box on and off one after the other.