SoFunction
Updated on 2025-04-14

Detailed explanation of the process of using C# to realize communication between host computer and PLC

1. Overview of communication between PLC and host computer

Communication between the host computer and the PLC is usually based on certain communication protocols. Common communication protocols include:

  • Modbus protocol:Modbus is a widely used industrial protocol, especially between PLC and host computer. It is divided into Modbus RTU (based on serial communication) and Modbus TCP (based on Ethernet communication).
  • Ethernet/IP protocol: Mainly used in industrial automation and process control fields, especially PLCs from brands such as Allen-Bradley.
  • PROFIBUS protocol: Commonly used in Siemens PLC.
  • OPC (OLE for Process Control) protocol: A common industrial communication protocol that can connect different devices and control systems.

In this article, we will focus on how to use itModbus protocolCommunication with PLC, especially how to communicate with PLC through C#.

2. Introduction to Modbus protocol

ModbusIt is a communication protocol launched by Modicon (now Schneider Electric) company, which is often used for data exchange of PLC, sensors, instruments and other equipment. The Modbus protocol has two main forms:

  • Modbus RTU (serial communication): Based on RS-232 or RS-485 serial communication, suitable for devices with far distances.
  • Modbus TCP (Ethernet Communication): Based on TCP/IP protocol, suitable for network-based device communication.

In the communication between the upper computer and the PLC, Modbus TCP is the most commonly used communication method, which connects the upper computer to the PLC through Ethernet.

3. Steps to implement communication with PLC in C#

To implement communication between the host computer and the PLC in C#, we need to follow the following steps:

  1. Select the right Modbus library: In C#, using ready-made third-party Modbus libraries can greatly simplify development work. For example,NModbusIt is a popular open source Modbus library that supports Modbus RTU and Modbus TCP protocols.
  2. Create a Modbus TCP client:passTcpClientConnect to the PLC and implement data reading and writing.
  3. Send and receive data: Data transmission is performed according to the address, register type and protocol format of the PLC.

Next, we will introduce in detail how to use C# andNModbusThe library implements communication with the PLC.

4. Install the NModbus library

First, we need to install it in the C# projectNModbuslibrary. It can be installed through the NuGet package manager.

  1. Open Visual Studio and create a new C# console application project.

  2. existtoolFrom the menu, selectNuGet Package Manager > Package Manager Console

  3. Enter the following command in the console to installNModbus

Install-Package NModbus4

at this time,NModbus4The library will be added to the project, which you can use in your code to implement Modbus communication.

5. C# realizes Modbus TCP and PLC communication

1. Create a Modbus TCP client

In this step, we will create a TCP client that communicates with the PLC through the Modbus TCP protocol.

Sample code:

using System;
using ;
using ;
using ;
 
class Program
{
    static void Main()
    {
        // PLC's IP address and port (usually Modbus TCP port is 502)        string plcIp = "192.168.1.100";
        int plcPort = 502;
 
        try
        {
            // Create a TCP client and connect to the PLC            TcpClient client = new TcpClient(plcIp, plcPort);
            ModbusTcpMaster master = (client);
 
            // Set the slave address of the PLC (generally default to 1)            byte slaveId = 1;
 
            // Read the Holding Registers of the PLC            ushort startAddress = 0;   // Start address            ushort numOfPoints = 10;   // Number of registers read            ushort[] values = (slaveId, startAddress, numOfPoints);
 
            // Output the register value returned by the PLC            ("PLC Holding Registers:");
            foreach (var value in values)
            {
                (value);
            }
 
            // Write data to the register of PLC            ushort[] writeValues = { 1234, 5678 }; // Data to be written            (slaveId, startAddress, writeValues);
            ("Data written to PLC!");
 
            // Close the connection            ();
        }
        catch (Exception ex)
        {
            ("Communication Error: " + );
        }
    }
}

Code explanation:

  1. Connect to PLC:useTcpClientConnect to the IP address and port of the PLC (usually Modbus TCP uses port 502).
  2. Create Modbus Master:pass(client)Create a Modbus TCP host (i.e., a host computer).
  3. Read data:passReadHoldingRegistersMethod reads the PLC's hold register data. The register address of the PLC starts from 0, and the return is aushort[]Array.
  4. Write data:passWriteMultipleRegistersMethod writes data to the specified register of the PLC.
  5. Close the connection: After completing the operation, close the TCP connection.

2. Handle exceptions and errors

During communication with the PLC, you may encounter problems such as network interruption, connection failure or protocol errors. Therefore, appropriate exception handling mechanisms must be added to the code to ensure the reliability of the system.

try
{
    // Network connection, data reading and other operations}
catch (SocketException ex)
{
    ("Socket error: " + );
}
catch (ModbusException ex)
{
    ("Modbus protocol error: " + );
}
catch (Exception ex)
{
    ("Unexpected error: " + );
}

3. Debugging and testing

Communication with the PLC can be ensured through debugging and testing. Usually, you can view the register value of the PLC through PLC programming software (such as Siemens Step 7, Allen-Bradley's RSLogix, etc.) to ensure that the data interaction between the upper computer and the PLC is normal.

6. Optimization and expansion

After implementing the basic Modbus communication function, the system can be optimized and expanded according to requirements:

  1. Multithreading and asynchronous operations: To improve performance, especially when communication with multiple devices simultaneously, asynchronous operations can be used (async/await) or multithreading techniques to avoid blocking the main thread.
  2. Data cache and processing: According to the amount of data collected, the data can be cached into the database for real-time processing and historical data analysis.
  3. Security: If communication needs to be carried out over the Internet, you can consider encrypting the communication (such as TLS/SSL) to improve security.
  4. Error retry mechanism: Increase the retry mechanism after communication failure to ensure stable communication can still be ensured in the event of network fluctuations.

7. Summary

Using C# to communicate with PLC mainly involves using the Modbus TCP protocol to realize connection, data reading and writing with PLC through C#. By usingNModbusLibrary can simplify the implementation of the Modbus protocol and avoid manually parsing data frames. This article shows the complete process from installing a library to writing code, and introduces common error handling and optimization methods. In this way, you can achieve reliable communication between the host computer and the PLC based on the Modbus protocol.

The above is a detailed explanation of the process of using C# to realize communication between host computers and PLCs. For more information about communication between C#, please pay attention to my other related articles!