65.9K
CodeProject is changing. Read more.
Home

Simple Modbus Slave Simulator

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.87/5 (8 votes)

Nov 6, 2007

CPOL
viewsIcon

110376

downloadIcon

12291

A simple Modbus slave simulator for testing Modbus master devices.

Screenshot - image294.gif

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--;
    }
    //0th item is crcLo
    returnResult[0] = usCRCLo;
    //1st item is crcHi
    returnResult[1] = usCRCHi;
    //2nd item is the total CRC16.
    //returnResult[2] = Convert.ToByte((usCRCHi << 8 | usCRCLo));
    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;
}