12

Using C#.net,WPF application.I'm going to connect to a device (MODBUS protocol), I have to calculate CRC (CRC16). Function which i use calculate normal crc16 and value is correct,but i want the value for CRC16(modbus) one.

Help me to sort out.

Alberto
  • 15,626
  • 9
  • 43
  • 56
user2720620
  • 153
  • 1
  • 1
  • 7

4 Answers4

8

There are a lot of resources online about the calculation of the crc16 for the modbus protocol.

For example:

http://www.ccontrolsys.com/w/How_to_Compute_the_Modbus_RTU_Message_CRC

http://www.modbustools.com/modbus_crc16.htm

I think that translating that code in c# should be simple.

Alberto
  • 15,626
  • 9
  • 43
  • 56
3

You can use this library:

https://github.com/meetanthony/crccsharp

It contains several CRC algorithms included ModBus.

Usage:

Download source code and add it to your project:

public byte[] CalculateCrc16Modbus(byte[] bytes)
{
  CrcStdParams.StandartParameters.TryGetValue(CrcAlgorithms.Crc16Modbus, out Parameters crc_p);
  Crc crc = new Crc(crc_p);
  crc.Initialize();
  var crc_bytes = crc.ComputeHash(bytes);
  return crc_bytes;
}
Mahdi Ataollahi
  • 4,544
  • 4
  • 30
  • 38
1

Just use:

public static ushort Modbus(byte[] buf)
        {
            ushort crc = 0xFFFF;
            int len = buf.Length;

            for (int pos = 0; pos < len; pos++)
            {
                crc ^= buf[pos];

                for (int i = 8; i != 0; i--)
                {
                    if ((crc & 0x0001) != 0)
                    {
                        crc >>= 1;
                        crc ^= 0xA001;
                    }
                    else
                        crc >>= 1;
                }
            }

            // lo-hi
            //return crc;

            // ..or
            // hi-lo reordered
            return (ushort)((crc >> 8) | (crc << 8));
        }

(curtesy of https://www.cyberforum.ru/csharp-beginners/thread2329096.html)

Nick Kovalsky
  • 5,378
  • 2
  • 23
  • 50
0

Boost CRC (Added due to title)

auto v = std::vector< std::uint8_t > { 0x12, 0x34, 0x56, 0x78 };
auto result = boost::crc_optimal<16, 0x8005, 0xFFFF, 0, true, true> {};
result.process_bytes(v.data(), v.size());
Edward Kigwana
  • 324
  • 2
  • 9