Search code examples
cesp32modbus

Modbus Register Map in C language ESp32


I am working with ESP32.. I want to communicate with external world with Modbus RTU. The ESP32 would be the slave. How can I create some modbus registers in c Language. Any idea ? It is just a simple table in C ? Thanks a lot


Solution

  • I did the same thing you want to do, not with ESP32, but it is the same.

    Basically, you put all the variables you want accessible as a modbus register in a precise location, probably a struct.

    For example

    struct modbusmap_t {
      uint16_t    speed;    // this has modbus address 0
      unit16_t    cooler;   // ...and this address 1
      ...
    } modbusregs;
    

    Your device is a slave, so you will implement a server which receives the modbus commands. When a request for writing the register "N" is received, you can simply access that register with:

    *((uint16_t *) &modbusregs + N) = requestvalue;
    

    For reading, the same applies:

    uint16result = *((uint16_t *) &modbusregs + N);
    

    There other ways to do this, for example through a union.

    To summarize, the key is to put all variables accessible as modbus registers in a known, ordered place, and use pointers or arrays to read/write them. For bits (modbus coils) some more trickery is necessary, but the idea is the same.

    In this example, "modbus register 0" maps to the variable "speed" in your source. Modbus has no concept of sign, but you can manage this, using 2-complement, or adding an offset (32000 means 0 speed, 32010 means speed 10, 31990 means speed -10 and so on).