User Tools

Site Tools

blog:2019-06-04_c_modbus_rtu_crc



2019-06-04 C# Modbus RTU CRC

  • We need calcuate the crc of Modbus RTU in C#
  • There is a tool to validate the crc value

C# CRC Calculate Code

  • My test code
    ...
            static byte[] var_ComData = new byte[256];
            static int var_ComDataLength = 0;
            static byte[] var_ComDataCRC = new byte[2];
    ...
    ...
            private void CalculateCRC()
            {
                ushort CRCFull = 0xFFFF; // CRC 的初值設成 0xFFFF
                byte CRCHigh = 0xFF, CRCLow = 0xFF; // CRC 的 High byte 和 Low byte
                char CRCLSB; // CRC Least signficant bit
    
                for (int i=0; i < var_ComDataLength; i++)
                {
                    CRCFull = (ushort)(CRCFull ^ var_ComData[i]); // exclusive or 
                    for (int j = 0; j < 8; j++)
                    {
                        CRCLSB = (char)(CRCFull & 0x0001); // 取得 Least signficant bit
                        CRCFull = (ushort)((CRCFull >> 1) & 0x7FFF); // 移去 Least signficant bit,前補0
    
                        if (CRCLSB == 1) // 如果 Least signficant bit 為 1
                            CRCFull = (ushort)(CRCFull ^ 0xA001);
                    }
                }
                var_ComDataCRC[1] = CRCHigh = (byte)((CRCFull >> 8) & 0xFF); // CRC high byte 在 後
                var_ComDataCRC[0] = CRCLow = (byte)(CRCFull & 0xFF); // CRC low byte 在前
            }
       ...
    

C# Modbus RTU CRC Calculate

On Line Modbus RTU CRC Calculator

  • In this site
  • There is a on line calculator for CRC calculate

TAGS

  • 374 person(s) visited this page until now.

Permalink blog/2019-06-04_c_modbus_rtu_crc.txt · Last modified: 2019/06/13 09:22 by jethro

oeffentlich