Using modbus TCP communication protocol


  • Ameba x 1


Modbus is a communication protocol which can be implemented on various interfaces, such as serial, ethernet, WiFi. In this example, we implement Modbus TCP on Ameba.
In Modbus protocol, the “Master” emits commands, and the “Slave” responds to the commands. In this example, Ameba will work as the “Slave”, and the “Master” will request to read information from Ameba.
  • Download Modbus tool
    There are a number of tools for Modbus. Here, we use a free command line tool called “modpoll”. Related documents can be found here:

    Unzip the downloaded file, then you can find different versions of the its executable file for different OS. For example, the Windows version is located in “win32\modpoll.exe”

  • Download Ameba Modbus library
    Please download Ameba Modbus library from:

    And follow the tutorial to install the .zip library to Ameba:

    In the library, we provide 32 16-bit buffers. The Modbus master will treat these buffers as the registers of Ameba. In the implementation, we can place the desired data in these buffers.

  • Run an example
    Open the sample code in “File” -> “Examples” -> “AmebaModbus” -> “simepletest”
    Please modify the sample code to provide the WiFi ssid/password information for WiFi connection. Then upload the sample to Ameba and press reset button.
  • Next, we use modpoll to connect to Ameba through modbus protocol. For example, in Windows OS please type the following command: modpoll -m tcp -t 4:int -r 40003, in which the last argument is the IP of Ameba, please fill in the correct value.

    Detailed description of each argument:

    In execution, modpoll reads the value of Ameba register at address 40003 every second. In the example, we put the system time of Ameba in the register, therefore the value modpoll gets is the system time of Ameba.

Code Reference

Create a ModbusTCP object:
ModbusTCP m;

In Setup(), we set the value of each (simulated) registers:

m.setFloat(S1_FloatConstant, PI);
m.setU32(S1_CurrentMillis, millis());
m.setU16(S1_FeetPerMile, 5280);

Next, connect Ameba to AP: (the required arguments are the same as Wifi begin())

m.begin(ssid, pass);

In loop(), check if there is connection from modbus master. If there is, handle the commands of modbus master:;

Finally, update the register value:

m.setU32(S1_CurrentMillis, millis());
Please confirm that QQ communication software is installed