SoFunction
Updated on 2025-03-06

Introduction to common methods of C# operating serial communication protocol Modbus

1. Read the coil status

        /// <summary>
        /// Read coil status test        /// </summary>
        static void Test_0x01()
        {
            ushort startAddr = 0;
            ushort readLen = 10;

            var a = (readLen);

            // ask            // byte[] requires a specified length; Linq is not supported            List<byte> command = new List<byte>();
            (0x01);// Slave No. 1            (0x01);// Function code: Read coil status            // Start address            ((startAddr)[1]);//
            ((startAddr)[0]);
            // Read count            ((readLen)[1]);
            ((readLen)[0]);

            // CRC
            command = CRC16(command);

            // Message assembly is completed            // Send-》SerialPort            SerialPort serialPort = new SerialPort("COM1", 9600, , 8, );
            // Open the serial port            ();

            ((), 0, );

            // Receive and parse response packets            byte[] respBytes = new byte[];
            (respBytes, 0, );

            // respBytes -> 01 01 02 00 00 B9 FC
            // Check a check bit            List<byte> respList = new List<byte>(respBytes);
            (0, 3);//Cut off: Slave address Function code Byte count            ( - 2, 2);//Cut off: Check bit
            ();
            var respStrList = (r => (r, 2)).ToList();
            var values = ("", respStrList).ToList();
            ();
            (c => (((()))));

        }

2. Read and hold register

        /// <summary>
        /// Read hold register        /// </summary>
        static void Test_0x03()
        {
            ushort startAddr = 0;
            ushort readLen = 10;

            // ask            // byte[] requires a specified length; Linq is not supported            List<byte> command = new List<byte>();
            (0x01);// Slave No. 1            (0x03);// Function code: Read-hold register            // Start address            ((startAddr)[1]);
            ((startAddr)[0]);
            // Read count            ((readLen)[1]);
            ((readLen)[0]);

            // CRC
            command = CRC16(command);

            // Message assembly is completed            // Send-》SerialPort            SerialPort serialPort = new SerialPort("COM1", 9600, , 8, );
            // Open the serial port            ();

            ((), 0, );

            // Receive and parse response packets            byte[] respBytes = new byte[];
            (respBytes, 0, );

            // respBytes -> 01 01 02 00 00 B9 FC
            // Check a check bit            List<byte> respList = new List<byte>(respBytes);
            (0, 3);//Cut off: Slave address Function code Byte count            ( - 2, 2);//Cut off: Check bit

            // Get the actual data part and perform data analysis            // To be clear: I read unsigned single precision            //byte[] data = new byte[2];
            //for (int i = 0; i < readLen; i++)
            //{
            // // Byte order problem Little endian Big endian            //    data[0] = respList[i * 2 + 1];
            //    data[1] = respList[i * 2];
            // // Convert to the desired actual number based on these two bytes            //    var value = BitConverter.ToUInt16(data, 0);
            //    (value);
            //}



            // To be clear: I read Float            byte[] data = new byte[4];
            for (int i = 0; i < readLen / 2; i++)
            {
                // Byte order problem Little endian Big endian                data[0] = respList[i * 4 + 3];
                data[1] = respList[i * 4 + 2];
                data[2] = respList[i * 4 + 1];
                data[3] = respList[i * 4];
                // Convert to the desired actual number based on these two bytes                var value = (data, 0);
                (value);
            }
        }

3. Write multiple hold registers

        /// <summary>
        /// Write multiple hold registers        /// </summary>
        static void Test_0x10()
        {
            ushort startAddr = 2;
            ushort writeLen = 4;
            float[] values = new float[] { 123.45f, 14.3f };

            // ask            // byte[] requires a specified length; Linq is not supported            List<byte> command = new List<byte>();
            (0x01);// Slave No. 1            (0x10);// Function code: Write multiple hold registers            // Write address            ((startAddr)[1]);
            ((startAddr)[0]);
            // Number of writes            ((writeLen)[1]);
            ((writeLen)[0]);


            // Get the value byte[]            List<byte> valueBytes = new List<byte>();
            for (int i = 0; i < ; i++)
            {
                List<byte> temp = new List<byte>((values[i]));
                ();// Adjust byte order                (temp);
            }

            // Number of bytes            ((byte));
            (valueBytes);

            // CRC
            command = CRC16(command);

            // Message assembly is completed            // Send-》SerialPort            SerialPort serialPort = new SerialPort("COM1", 9600, , 8, );
            // Open the serial port            ();

            ((), 0, );
        }

4. CRC verification

        static List<byte> CRC16(List<byte> value, ushort poly = 0xA001, ushort crcInit = 0xFFFF)
        {
            if (value == null || !())
                throw new ArgumentException("");

            //Operation            ushort crc = crcInit;
            for (int i = 0; i < ; i++)
            {
                crc = (ushort)(crc ^ (value[i]));
                for (int j = 0; j < 8; j++)
                {
                    crc = (crc & 1) != 0 ? (ushort)((crc >> 1) ^ poly) : (ushort)(crc >> 1);
                }
            }
            byte hi = (byte)((crc & 0xFF00) >> 8);  //High position            byte lo = (byte)(crc & 0x00FF);         //Low position
            List<byte> buffer = new List<byte>();
            //Add to verify the original value            (value);
            //Add a check bit value            (lo);
            (hi);
            
            // Add the original check value to return            return buffer;
        }

This is all about this article about C# operation serial communication protocol Modbus. I hope it will be helpful to everyone's learning and I hope everyone will support me more.