Modbus programming in C# including example code for both TCP and RTU communication

Introduction to advanced Modbus programming in C# includes example code for TCP and RTU communication, covering additional functionalities such as writing data and handling exceptions.
Modbus programming in c#

Example Code for TCP Communication:

csharp
using Modbus.Device; using System; using System.Net.Sockets; class Program { static void Main(string[] args) { string ipAddress = "192.168.1.1"; // IP address of the Modbus device int port = 502; // Modbus TCP port number TcpClient client = new TcpClient(ipAddress, port); ModbusIpMaster master = ModbusIpMaster.CreateIp(client); try { // Read holding registers from Modbus device ushort startAddress = 0; // Starting address of the registers ushort numRegisters = 10; // Number of registers to read ushort[] registers = master.ReadHoldingRegisters(1, startAddress, numRegisters); for (int i = 0; i < registers.Length; i++) { Console.WriteLine("Register {0}: {1}", startAddress + i, registers[i]); } // Write data to holding registers ushort[] dataToWrite = { 100, 200, 300 }; // Data to write ushort writeStartAddress = 10; // Starting address to write data master.WriteMultipleRegisters(1, writeStartAddress, dataToWrite); Console.WriteLine("Data written successfully."); client.Close(); } catch (ModbusException ex) { Console.WriteLine("Modbus Exception: {0}", ex.Message); } catch (SocketException ex) { Console.WriteLine("Socket Exception: {0}", ex.Message); } catch (Exception ex) { Console.WriteLine("Exception: {0}", ex.Message); } Console.ReadLine(); } }

Example Code for RTU Communication:
csharp
using Modbus.Device; using System; using System.IO.Ports; class Program { static void Main(string[] args) { string portName = "COM1"; // Serial port name int baudRate = 9600; // Baud rate Parity parity = Parity.None; // Parity int dataBits = 8; // Data bits StopBits stopBits = StopBits.One; // Stop bits SerialPort port = new SerialPort(portName, baudRate, parity, dataBits, stopBits); ModbusSerialMaster master = ModbusSerialMaster.CreateRtu(port); try { // Read holding registers from Modbus device byte slaveId = 1; // Modbus slave ID ushort startAddress = 0; // Starting address of the registers ushort numRegisters = 10; // Number of registers to read ushort[] registers = master.ReadHoldingRegisters(slaveId, startAddress, numRegisters); for (int i = 0; i < registers.Length; i++) { Console.WriteLine("Register {0}: {1}", startAddress + i, registers[i]); } // Write data to holding registers ushort[] dataToWrite = { 100, 200, 300 }; // Data to write ushort writeStartAddress = 10; // Starting address to write data master.WriteMultipleRegisters(slaveId, writeStartAddress, dataToWrite); Console.WriteLine("Data written successfully."); port.Close(); } catch (ModbusException ex) { Console.WriteLine("Modbus Exception: {0}", ex.Message); } catch (IOException ex) { Console.WriteLine("IO Exception: {0}", ex.Message); } catch (Exception ex) { Console.WriteLine("Exception: {0}", ex.Message); } Console.ReadLine(); } }


We use the NModbus library for Modbus communication in C# in these examples. The code demonstrates additional functionalities, such as writing data to hold registers and handling exceptions.

After establishing the connection with the Modbus device, we attempt to read a range of holding registers using the ReadHoldingRegisters method. We then iterate through the received register values and display them on the console.

Next, we write data to the holding registers using the WriteMultipleRegisters method. We specify the slave ID, the starting address to write data, and the data values to be written.

We wrap the Modbus-specific exceptions (ModbusException) and general exceptions (Exception) in try-catch blocks to handle exceptions. This allows us to handle potential errors and provide meaningful error messages gracefully.

Make sure to replace the IP address, port, and serial port settings with the appropriate values based on your Modbus device configuration.

These examples provide a starting point for advanced Modbus programming in C#. You can further explore the NModbus library documentation for more functionalities, such as reading/writing coils, input registers, or handling different Modbus exception codes.