Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / desktop / WinForms

Simple Modbus Slave Simulator

2.87/5 (8 votes)
6 Nov 2007CPOL 1   12.3K  
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:

C++
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;
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)