Modbus TCP Server

Modbus TCP Server

This tutorial shows how to set up a Modbus TCP server on the NEXTuino BASE. The server controls an onboard LED via a Modbus coil at address 0x00.

Required Libraries

  • SPI
  • Ethernet
  • ArduinoRS485
  • ArduinoModbus

Hardware Setup

Connect the NEXTuino BASE to your network via an Ethernet cable.

Configuration

Define the MAC address and IP address for the Modbus TCP server:

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192, 168, 1, 177);

Server Initialization

Initialize the Ethernet interface and start the Modbus TCP server:

Ethernet.begin(mac, ip);
EthernetServer ethServer(502);
ModbusTCPServer modbusTCPServer;

ethServer.begin();
modbusTCPServer.begin();

Configure a single coil at address 0x00:

modbusTCPServer.configureCoils(0x00, 1);

Handling Client Connections

In the main loop, accept incoming connections and poll for Modbus requests:

EthernetClient client = ethServer.available();
if (client) {
    modbusTCPServer.accept(client);
    if (client.connected()) {
        modbusTCPServer.poll();
        updateLED();
    }
}

Reading the Coil and Controlling the LED

The updateLED() function reads the coil state and sets the LED accordingly:

void updateLED() {
    int coilValue = modbusTCPServer.coilRead(0x00);
    if (coilValue == 1) {
        digitalWrite(LED_BUILTIN, HIGH);
    } else {
        digitalWrite(LED_BUILTIN, LOW);
    }
}

Full Example

The complete example is available on GitHub:
EthernetModbusServerLED.ino