
Introduction
The Modbus Software Slave simulates a serial modbus slave device. You can configure the slave address, registers, and communication settings. It only responds to function 03, and only works in RTU mode.
Background
Some Modbus knowledge is required.
Using the code
The static CRCStuff
class might be useful for basic CRC16 calculations. Here is the code:
public static byte[] calculateCRC(ref byte[] messageArray, int dataLength)
{
byte usCRCHi = 0xFF;
byte usCRCLo = 0xFF;
byte[] returnResult = { 0x00, 0x00, 0x00 };
int index = 0;
int messageIndex = 0;
while (dataLength > 0)
{
index = usCRCLo ^ messageArray[messageIndex];
usCRCLo = Convert.ToByte(usCRCHi ^ crcHi[index]);
usCRCHi = crcLo[index];
messageIndex++;
dataLength--;
}
returnResult[0] = usCRCLo;
returnResult[1] = usCRCHi;
return returnResult;
}
public static bool checkCRC(ref byte[] messageToCheck, int numberOfBytes)
{
byte[] calculatedCRC;
calculatedCRC = calculateCRC(ref messageToCheck, numberOfBytes - 2);
if (calculatedCRC[0] == messageToCheck[numberOfBytes - 2] &&
calculatedCRC[1] == messageToCheck[numberOfBytes - 1])
return true;
return false;
}