Modbus TCP Server Client I/O

Introduction

This guide covers setting up Modbus TCP communication between a client and server using NEXTuino and an Ethernet shield. The client reads and writes inputs and outputs; the server synchronizes its state with the client.

Prerequisites

  • Installed Arduino IDE
  • NEXTuino board (MAXI, MAXI Automation, or MEGA)
  • Basic understanding of Modbus TCP and Ethernet setup

Example Code

Download the example code from GitHub:

Modbus TCP Client

Step 1: Setup the Arduino Environment

  • Include the necessary libraries: ArduinoRS485, ArduinoModbus, NEXTuino, SPI, Ethernet

Step 2: Initialize Ethernet and Modbus TCP Client

In setup():

  1. Start Ethernet: Ethernet.begin(mac, ip)
  2. Check hardware and cable connection
  3. Initialize Modbus TCP client: modbusTCPClient.begin(server, 502)

Step 3: Configure Digital and Analog Pins

In loop():

Digital Inputs and Coils:

  • Declare array slaveInputs[] to store slave digital input states
  • Read using modbusTCPClient.discreteInputRead()
  • Sync slave inputs to master outputs using digitalWrite()
  • Write master digital input to slave using modbusTCPClient.coilWrite()

Analog Inputs and Holding Registers:

  • Declare array slaveInRegisters[] for slave holding register states
  • Read analog inputs with modbusTCPClient.inputRegisterRead()
  • Sync master analog outputs with analogWrite()
  • Update slave holding registers with modbusTCPClient.holdingRegisterWrite()

Modbus TCP Server

Step 1: Setup the Arduino Environment

Include the same libraries: ArduinoRS485, ArduinoModbus, NEXTuino, SPI, Ethernet

Step 2: Initialize Ethernet and Modbus TCP Server

In setup():

  1. Start Ethernet: Ethernet.begin(mac, ip)
  2. Start Modbus TCP server: modbusTCPServer.begin()
  3. Configure Modbus registers:
    • modbusTCPServer.configureCoils()
    • modbusTCPServer.configureDiscreteInputs()
    • modbusTCPServer.configureHoldingRegisters()
    • modbusTCPServer.configureInputRegisters()

Step 3: Configure Digital and Analog Pins

  • Use pinMode() to define pins as INPUT or OUTPUT
  • Initialize output pins to LOW state
  • Set up analog output pins for holding registers with analogWrite()

Step 4: Synchronizing Coils and Registers

In loop():

  1. Client Connection: Wait with ethernetServer.available(), accept with modbusTCPServer.accept(client)
  2. In executeSynchronization():
    • Read coil states with modbusTCPServer.coilRead(), update outputs with digitalWrite()
    • Read input pins with digitalRead(), update coil registers with modbusTCPServer.coilWrite()
    • Write holding register values to PWM outputs with analogWrite()
    • Read analog inputs, update input registers with modbusTCPServer.inputRegisterWrite()

Conclusion

You have configured Modbus TCP communication between a NEXTuino client and server. The client reads and writes digital and analog I/Os, while the server synchronizes its state accordingly.