Roadmap › Industrial Automation — PLC, SCADA, Modbus and OPC UA › Module: Supervisory Systems and Communication
Lessons in this course (10)

9. Connecting PLCs to .NET applications

Advanced★ Must knowLesson 9 of 10

Read a Modbus TCP register with NModbus:

csharp
using System.Net.Sockets;
using NModbus;

using var tcp = new TcpClient("192.168.0.10", 502);
var master = new ModbusFactory().CreateMaster(tcp);
ushort[] regs = master.ReadHoldingRegisters(slaveAddress: 1, startAddress: 0, numberOfPoints: 2);
float temperature = BitConverter.ToSingle(BitConverter.GetBytes((regs[0] << 16) | regs[1]), 0);  // word order per device manual
master.WriteSingleRegister(1, 10, 750);   // write setpoint 75.0 (scaled ×10)

Subscribe to OPC UA values with the OPC Foundation .NET stack (simplified):

csharp
var endpoint = CoreClientUtils.SelectEndpoint(config, "opc.tcp://plc1:4840", useSecurity: true);
using var session = await Session.Create(config, new ConfiguredEndpoint(null, endpoint), false, "MES", 60000, new UserIdentity(), null);

var subscription = new Subscription(session.DefaultSubscription) { PublishingInterval = 1000 };
var item = new MonitoredItem(subscription.DefaultItem) { StartNodeId = "ns=3;s=\"Line1\".\"Temperature\"", SamplingInterval = 500 };
item.Notification += (mi, e) =>
{
    foreach (var value in mi.DequeueValues())
        Console.WriteLine($"{mi.StartNodeId} = {value.Value} ({value.StatusCode}) @ {value.SourceTimestamp}");
};
subscription.AddItem(item);
session.AddSubscription(subscription);
subscription.Create();

Architecture for a plant-data application:

text
PLCs (Modbus/S7/EtherNet/IP) ─► Gateway / OPC UA server ─► Edge service (.NET Worker, buffering)
     ─► MQTT broker or Azure IoT Hub ─► Stream processing ─► SQL Server / time-series DB ─► Dashboards, MES, ML

Design rules: read-mostly (writes to PLCs only through controlled, audited paths with interlocks staying in the PLC), buffer data at the edge when the network drops (store-and-forward), use source timestamps and status/quality codes, keep OT networks segmented.