Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function to calculate CRC16 (Modbus) value

Tags:

c#

modbus

crc16

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.

like image 637
user2720620 Avatar asked Aug 30 '13 06:08

user2720620


2 Answers

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.

like image 92
Alberto Avatar answered Oct 22 '22 10:10

Alberto


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;
}
like image 22
Mahdi Ataollahi Avatar answered Oct 22 '22 12:10

Mahdi Ataollahi