SubName: Modbus CRC-16 is used to ensure data integrity in Modbus RTU (Remote Terminal Unit) communications.
Description: This function takes a command message Bytes and performs the necessary bitwise operations to generate a 16-bit CRC checksum, and outputs this checksum as a hexadecimal string.
The following code calculates the Modbus RTU CRC-16 (LSB-first / little-endian), the standard CRC (Cyclic Redundancy Check) used for Modbus frames.
Let's use 010107DE000A as an example to calculated it's Modbus CRC-16 value, which is 43DD.
The full Modbus RTU frame that would be transmitted is 01 01 07 DE 00 0A 43 DD.
Here is the byte by byte Breakdown
Enjoy...
Description: This function takes a command message Bytes and performs the necessary bitwise operations to generate a 16-bit CRC checksum, and outputs this checksum as a hexadecimal string.
The following code calculates the Modbus RTU CRC-16 (LSB-first / little-endian), the standard CRC (Cyclic Redundancy Check) used for Modbus frames.
Let's use 010107DE000A as an example to calculated it's Modbus CRC-16 value, which is 43DD.
How to use:
Dim BC As ByteConverter
Dim Data() As Byte = BC.HexToBytes("010107DE000A")
Log(CalcModbusCRC(Data))
Modbus CRC-16:
Sub CalcModbusCRC(Bytes() As Byte) As String
Dim CRCr As Int = 0xFFFF
For i = 0 To Bytes.Length - 1
CRCr = Bit.Xor(CRCr, Bit.And(Bytes(i), 0xFF))
For j = 0 To 7
If (Bit.And(CRCr, 1) = 1) Then
CRCr = Bit.Xor(Bit.ShiftRight(CRCr, 1), 0xA001)
Else
CRCr = Bit.ShiftRight(CRCr, 1)
End If
Next
Next
'Low byte first (Modbus standard)
Dim low As Int = Bit.And(CRCr, 0xFF)
Dim high As Int = Bit.And(Bit.ShiftRight(CRCr, 8), 0xFF)
Return Bit.ToHexString(high).ToUpperCase & Bit.ToHexString(low).ToUpperCase
End Sub
The full Modbus RTU frame that would be transmitted is 01 01 07 DE 00 0A 43 DD.
Here is the byte by byte Breakdown
| Hex Value | Description | |
|---|---|---|
| 01 | Slave Address (Unit ID): The address of the device being targeted. | |
| 01 | Function Code: Read Coils (Discrete Outputs). | |
| 07DE | Starting Address: The address of the first coil to read (7DE hex = 2014 decimal). | |
| 000A | Quantity: The number of coils to read (0A hex = 10 decimal). | |
| 43 | CRC Low Byte: The Least Significant Byte of the CRC. | |
| DD |
|
Enjoy...
Last edited: