Configuring Modbus TCP Over TRB140 VPN: Modicon TM251 to TM221

Claire Rousseau10 min read
ModbusSchneider ElectricTutorial / How-to
Licensed PE Working through this on a live machine? A Maine-licensed engineer can take it from here — included with IMD hardware, by the hour for everything else. Book an engineer

Configuring Modbus TCP Between Modicon TM251 and TM221 Over a TRB140 VPN

Bridging Modicon M251 and M221 logic controllers with a Modbus TCP link across two Teltonika TRB140 industrial gateways requires careful subnet planning, VPN tunnel configuration, and explicit firewall rules. This guide walks through the complete setup, from IP addressing to commissioning verification, using Schneider Electric's Modicon TM251MESE controller as the Modbus TCP master and the Modicon TM221CE24R as the Modbus TCP slave.

1. Overview and Architecture

The target topology is a site-to-site VPN between two remote installations. Each site hosts a TRB140 cellular gateway that bridges the local Ethernet network (where the Modicon controller resides) to a public LTE/4G bearer. An IPsec or OpenVPN tunnel terminates on a central VPN concentrator, and Modbus TCP frames from the TM251MESE travel across that tunnel to the TM221CE24R.

Modbus TCP Across TRB140 Site-to-Site VPN Site A (192.168.2.0/24) TM251MESE Master 192.168.2.10 TRB140 #1 LAN: 192.168.2.1 VPN Tunnel 10.10.0.0/30 TRB140 #2 LAN: 192.168.3.1 Site B (192.168.3.0/24) TM221CE24R Slave 192.168.3.20

The critical design rule when extending Modbus TCP over a routed VPN is that the two LAN segments must use different IP subnets. Routing protocols cannot forward traffic between two interfaces that share the same subnet mask and address range, so the remote TM221 will appear unreachable. Resolving this requires either re-addressing one site or using 1-to-1 NAT on the gateway; re-addressing is the cleanest approach and the one used in this guide.

2. Prerequisites

Before commissioning, confirm the following:

  • Two Teltonika TRB140 gateways running firmware TRB1_R_00.07.06 or later (verify under System > Firmware). The TRB140 firmware page lists the latest stable builds.
  • Active SIM cards with public or private APN credentials for each TRB140.
  • Modicon TM251MESE (M251 logic controller, Ethernet) with EcoStruxure Machine Expert (formerly SoMachine) V1.1 or newer.
  • Modicon TM221CE24R (M221 logic controller, relay outputs) with SoMachine Basic V1.6 or newer.
  • Ethernet cabling, a managed switch at each site, and laptop access to the LAN.
  • VPN credentials: pre-shared key (IPsec) or certificates/keys (OpenVPN, WireGuard).
Subnet Rule: Site A and Site B must NOT share the same /24 subnet. The default TRB140 LAN address is 192.168.2.1/24; change Site B to 192.168.3.1/24 (or any other non-overlapping range) before continuing.

3. Network Addressing Plan

Lay out the addressing before configuring any device. The table below is the working plan used in this guide.

Device Role Interface IP Address Subnet Mask Default Gateway
TRB140 #1 VPN client LAN 192.168.2.1 255.255.255.0 — (DHCP from cellular)
TM251MESE Modbus TCP master ETH1 192.168.2.10 255.255.255.0 192.168.2.1
TRB140 #2 VPN server / peer LAN 192.168.3.1 255.255.255.0
TM221CE24R Modbus TCP server ETH 192.168.3.20 255.255.255.0 192.168.3.1
VPN tunnel tun0 10.10.0.1 ↔ 10.10.0.2 255.255.255.252

Modbus TCP default port 502/TCP is used throughout. If the cellular provider blocks port 502 (some carriers do), switch to a non-standard high port such as 2502/TCP on the slave and add a port-forward or NAT translation on the TRB140.

4. TRB140 VPN Configuration

The TRB140 supports IPsec, OpenVPN, and WireGuard tunnels. For Modicon controllers, IPsec IKEv2 with PSK gives the lowest overhead and best compatibility. Configuration is performed through the WebUI (https://192.168.2.1) or via the Teltonika TRB140 VPN wiki.

4.1 TRB140 #1 (Site A — VPN Initiator)

  1. Log in to https://192.168.2.1. Default credentials: admin / admin01.
  2. Navigate to Services > VPN > IPsec.
  3. Create a new IPsec connection with the following parameters:
Parameter Value
Remote endpoint Public IP or DDNS of TRB140 #2
Authentication Pre-shared key
PSK 32-character random string (e.g. A7b3K9pQ2rT8vX1zM5nL4jH6cF0sD9eG)
IKE version IKEv2
Encryption AES-256-GCM
Integrity SHA2-256
DH group 14 (2048-bit)
Local subnet 192.168.2.0/24
Remote subnet 192.168.3.0/24
NAT traversal Enabled
DPD delay / timeout 30 s / 120 s
  1. Click Save & Apply. The TRB140 will attempt to bring up the SA.
  2. Verify the SA under Status > IPsec; look for STATE_MAIN_I4 and CHILD_SA entries.

4.2 TRB140 #2 (Site B — VPN Responder)

Mirror the configuration with inverted local/remote subnets. The PSK, encryption suite, and DH group must match exactly. Add a static route under Network > Routing > Static routes to direct 192.168.2.0/24 traffic to the IPsec interface.

4.3 Firewall Rules

By default, the TRB140 blocks forwarded traffic. Add an explicit rule on each gateway:

Action:      Accept
Protocol:    TCP
Source:      192.168.2.0/24 (Site A) / 192.168.3.0/24 (Site B)
Destination: 192.168.3.20 / 192.168.2.10
Port:        502
Forward to:  ipsec0

For the ICMP path-check rule used during commissioning:

Action: Accept | Protocol: ICMP | Source: 192.168.2.0/24 | Destination: 192.168.3.0/24

Detailed procedures are documented in the TRB140 firewall configuration guide.

5. Modicon TM251MESE Master Configuration (EcoStruxure Machine Expert)

The TM251MESE is configured as a Modbus TCP client (master). The Modicon M251 supports up to 16 simultaneous Modbus TCP connections using the ModbusTcpMaster function block from the Communication library.

5.1 Project Setup

  1. Launch EcoStruxure Machine Expert, open the project, and select the TM251MESE controller.
  2. In the device tree, double-click Ethernet_1 (ETH1) and set:
    • IP address: 192.168.2.10
    • Subnet mask: 255.255.255.0
    • Gateway: 192.168.2.1
  3. Add the gateway router to the configuration: Project > Add Device > Router. Set its address to 192.168.2.1 so generated routes reach the WAN side.

5.2 Declare the Modbus TCP Slave Channel

Right-click Modbus_TCP_Master > Add Channel. Configure the channel as follows:

Parameter Value
Name MBTCP_To_TM221
Driver Modbus TCP Master
Remote IP 192.168.3.20
Remote port 502
Connection timeout 3000 ms
Response timeout 2000 ms
Polling cycle 200 ms
Retry count 3

5.3 Sample ST Code — Reading Three Holding Registers

The slave exposes three words in memory (e.g. %MW100, %MW101, %MW102). The master reads them and copies the values into local variables.

PROGRAM PLC_PRG
VAR
    fbMBMaster : ModbusTcpMaster;
    xExecute   : BOOL := TRUE;
    xDone      : BOOL;
    xError     : BOOL;
    eError     : ModbusTcpMasterErrors;
    arrData    : ARRAY[0..2] OF WORD;
    wSlaveAddr : WORD := 1;     (* Modbus unit ID of TM221 *)
    wQuantity  : WORD := 3;
    wStartAddr : WORD := 100;   (* Maps to %MW100 on TM221 *)
END_VAR

fbMBMaster(
    xExecute    := xExecute,
    xConnect    := TRUE,
    sRemoteHost := '192.168.3.20',
    uiTcpPort   := 502,
    eFunction   := MODBUS_FC_READ_HOLDING_REGISTERS,
    uiUnitId    := wSlaveAddr,
    uiStartAddr := wStartAddr,
    uiQuantity  := wQuantity,
    pDestAddr   := ADR(arrData),
    cbDestLen   := SIZEOF(arrData),
    xDone       => xDone,
    xError      => xError,
    eError      => eError
);

IF xError THEN
    (* Trigger alarm, increment retry counter *)
    CASE eError OF
        MODBUS_TCP_ERR_TIMEOUT      : ; (* link down *)
        MODBUS_TCP_ERR_REMOTE_CLOSED: ; (* TCP closed by remote *)
        MODBUS_TCP_ERR_GATEWAY_UNREACHABLE: ; (* check VPN *)
    END_CASE;
END_IF;

6. Modicon TM221CE24R Slave Configuration (SoMachine Basic)

The Modicon TM221CE24R acts as a Modbus TCP server. Configuration is performed in SoMachine Basic using the built-in Ethernet port.

6.1 Ethernet and Modbus Server Settings

  1. Open the project, navigate to TM221CE24R > Ethernet port.
  2. Set IP address to 192.168.3.20, mask 255.255.255.0, gateway 192.168.3.1.
  3. Enable Modbus TCP Server and confirm the listening port is 502.
  4. Set Number of connected clients to 4 (TM251 holds 1, the remaining slots allow HMI access).

6.2 Mapping Internal Variables to Holding Registers

In SoMachine Basic, drag three MEMORY WORD symbols from the toolbox and assign them to addresses %MW100, %MW101, and %MW102. These become Modbus holding registers 100, 101, and 102 when accessed through the Modbus TCP server (offset = address - 1; so register 100 maps to offset 99, see Modbus Application Protocol V1.1b3).

6.3 Optional Access Control

SoMachine Basic supports an IP-based access list. To restrict the slave to only the master and an HMI, populate the Authorized clients list with 192.168.3.0/24 and 10.10.0.0/30 ranges; other clients receive an immediate TCP close.

7. Commissioning and Verification

Validate the link in this order — IP, VPN tunnel, Modbus TCP application layer. Skipping steps makes it hard to localize faults.

7.1 Layer-3 Verification

  1. From a laptop on Site A, ping the remote TM221: ping 192.168.3.20. Expect < 150 ms RTT over LTE.
  2. From the TRB140 #1 CLI (or SSH), run traceroute 192.168.3.20. The first hop after the LAN should be the IPsec gateway address (e.g. 10.10.0.2).

7.2 Modbus Application Layer Verification

  1. Launch the EcoStruxure Machine Expert Logic Builder's Modbus I/O Scanner test page; poll the three registers and confirm non-zero replies when the TM221 sets values.
  2. Capture a frame with Wireshark using the filter modbus && ip.addr == 192.168.3.20. Confirm a valid MBAP header (transaction ID, protocol ID = 0, length, unit ID) and a function code 0x03 response.
  3. Force a slave-side fault by unplugging the TM221 Ethernet cable. The master's xError should assert within Response timeout and clear automatically when the link returns.

7.3 Latency Tuning

Cellular VPNs add 30–80 ms one-way latency. For deterministic polling:

  • Set Modbus TCP Response timeout to at least 3000 ms.
  • Set Polling cycle to 500 ms minimum; faster rates risk buffer starvation.
  • Enable QoS on the TRB140 WAN interface with a DSCP value of 46 (EF) for UDP 4500/500 and TCP 502 traffic.

8. Troubleshooting Matrix

Symptom Likely Cause Diagnostic Step Remediation
Master xError = GATEWAY_UNREACHABLE VPN tunnel down or mismatched PSK Check Status > IPsec; review /var/log/ipsec.log Re-enter PSK, confirm encryption suites match
Ping to TM221 fails but ping to TRB140 #2 succeeds Static route missing on TRB140 #2 Show routing table from TRB140 #2 CLI Add 192.168.2.0/24 → ipsec0 route
TCP connect on port 502 refused Modbus TCP server disabled on TM221 SoMachine Basic: verify Modbus Server = ON Enable server, rebuild and download project
Reads return 0x0000 even though TM221 memory is non-zero Modbus offset vs. address confusion Read raw holding register 0 to confirm; check mapping Use Modbus address = M221 address - 1
Intermittent timeouts during peak hours Cellular bearer congestion or NAT timeout Track SA rekeying logs; ping every 10 s Enable DPD, lower MTU to 1380, force TCP keepalives
Connection establishes then drops after 60 s NAT timeout on cellular carrier Look for ICMP unreachable or RST in capture Enable NAT-T keepalives every 20 s; add firewall rule for ISAKMP
Same subnet on both sites — traffic never leaves LAN Original TRB140 default 192.168.2.1/24 used on both gateways Confirm Site B LAN ≠ Site A LAN Re-address Site B to 192.168.3.x; restart switches

9. Performance and Sizing Notes

A single Modbus TCP transaction over VPN carries a typical payload of 12 + (2 × N) bytes for N registers, plus IPsec overhead. With AES-256-GCM the additional encapsulation is ~50 bytes. Over LTE with 80 ms RTT, the achievable polling rate for 3 registers is approximately:

f_max ≈ 1 / (RTT + 2 × t_process) ≈ 1 / (0.16 + 0.04) ≈ 5 Hz

If you need higher rates, batch more registers per request (up to 125 words per FC03 transaction) and switch to FC23 (Read/Write Multiple Registers) for read-then-act patterns.

10. Security Hardening

  • Replace the default admin / admin01 TRB140 credentials; rotate the PSK every 90 days.
  • Disable HTTP management from the WAN; enable HTTPS only.
  • Add an explicit firewall rule denying all inbound traffic except IPsec (UDP 500/4500) and the explicit Modbus port forward.
  • Lock the TM221 to a single authorized client IP (the master's VPN address).
  • Where the application allows, switch to Modbus TCP Security (Modbus/TLS) as defined in the Modbus Organization specifications.
Safety Notice: Modbus TCP is not a safety-rated protocol. When controlling protective functions across a VPN, use the M221's dedicated safety I/O and a separate, hardwired safety relay that is independent of the cellular link.

11. Frequently Asked Questions

Why does Modbus TCP fail when both TRB140 units use the default 192.168.2.x subnet?

Routed networks cannot forward traffic between two interfaces that share the same subnet. The VPN software sees the destination as local and never pushes packets through the tunnel. Re-address one site (for example 192.168.3.0/24) so the subnets are unique.

Can I keep the original IP on the remote TM221CE24R using 1-to-1 NAT on the TRB140?

Yes. Under Network > Firewall > NAT Rules create a dst-nat entry that maps a virtual address (e.g. 192.168.2.50) to the real TM221 address 192.168.3.20:502. This avoids PLC reconfiguration but adds a layer of indirection that complicates diagnostics.

What is the maximum number of Modbus TCP clients the TM221CE24R supports?

The TM221CE24R supports up to 4 simultaneous Modbus TCP clients. Reserve one slot for the M251 master and the remaining three for HMIs or the EcoStruxure Machine Expert programming software.

Why does the VPN tunnel drop every 60 seconds on a cellular link?

Most mobile carriers drop NAT mappings after 60 s of inactivity. Enable Dead Peer Detection (DPD) on the TRB140 IPsec profile with a delay of 20 s and a timeout of 60 s, and turn on NAT-Traversal keepalives. The TM251's Modbus polling at 500 ms also keeps the SA alive.

Do I need a static public IP on the remote TRB140?

Not necessarily. Use a dynamic-DNS service (such as the TRB140's built-in No-IP or DynDNS client) on TRB140 #2 and configure TRB140 #1 to resolve the hostname in its IPsec remote endpoint. Re-key the tunnel automatically by enabling DPD so it recovers when the public IP changes.

Back to blog