Application Manual for Modbus Protocol Stack Based on mnModbus

freeFree Technical Resource

This content is free to read, suitable for basic learning and search traffic.

Application Manual for Modbus Protocol Stack Based on mnModbus缩略图

Chapter 1 Preface

Modbus is the world's first bus protocol truly used in industrial fields. Modbus communication is widely used and convenient in industrial network communication, and is welcomed by everyone.

1.1 Reasons for Writing

We have been using Modbus communication protocol multiple times in our own products and projects. Every time, users develop or search for source code that meets the requirements online. But each application is different and requires a lot of repetitive labor. Moreover, the close integration of protocol stations with application software also makes the code somewhat chaotic. So I have always wanted to develop a more universal protocol stack that can be reused in subsequent projects without having to write it every time. Now take advantage of the project development opportunity to develop your own Modbus protocol stack.

1.2, Copyright Notice

Although this software was originally developed for our own use, it is now open source on GitHub. So anyone can copy, spread, and use it without any restrictions, whether for personal learning or commercial applications. We welcome discussions on application methods and modifications, but we are not responsible for any problems that may arise during use. The software source code and its description can be freely downloaded from GitHub, download link: https://github.com/foxclever/Modbus

The software source code and its instructions can be freely downloaded from GitHub, download link: https://github.com/foxclever/Modbus

1.3, Update Record

In the previous version, we have implemented Modbus RTU based on serial links and Modbus TCP based on Ethernet. In this version, we have added Modbus ASCII based on serial links. And made corrections to the known issues in the previous version. The software design and update records of this document are as follows:

The software design and update records of this document are as follows:

versionupdate instructionsAuthorDate
V1.0.0First edition, consisting of 5 chapters, introducing the main API functionsMu NanMay 8, 2015
V1.1.0Added Chapters 6 and 7Mu NanDecember 23, 2016
V1.1.5Modified most of the content in Chapters 3, 4, and 5KonanFebruary 20, 2018
V2.0.0Added ASCII related content and modified known issuesKonanSeptember 18, 2018
V2.1.0Added class capacity for RTU and ASCII multi master station operations; Added content on TCP client multi segment operations.KonanApril 29, 2019

Chapter 2: PDU Functions

In the application data unit, we handle the basic message formats for Modbus data communication, which are generally used. The current version only supports 01, 02, 03, 04, 05, 06, 15, and 16 function codes.

4.1.1 Function code enumeration

/*Define Modbus operation function codes, supporting 01, 02, 03, 04, 05, 06, 15, and 16 function codes*/

typedef enum {

ReadCoilStatus=0x01, /*Read coil status (read the status of multiple output bits)*/

ReadInputStatus=0x02, /*Read input bit status (read the status of multiple input bits)*/

ReadHoldingRegister=0x03, /*Read hold register (read values from multiple hold registers)*/

ReadInputRegister=0x04, /*Read input registers (read values from multiple input registers)*/

WriteSingleCoil=0x05,/* Force Single Coil (Force Single Output Bit Status) */

WriteSingleRegister=0x06,/* Pre fabricated Single Register (Set a Register Value) */

WriteMultipleCoil=0x0F, /*Force multiple coils (force multiple output bit states) */

WriteMultipleRegister=0x10/* Pre set multiple registers (set values for multiple registers) */

} FunctionalCode;

4.1.2, Modbus Status Enumeration

/*Define the error code when receiving instructions to detect errors*/

typedef enum{

MB_OK=0x00,

InvalidFunctionCode=0x01, //Illegal function code

IllegalDataAddress=0x02, //Illegal data address

IllegalDataValues=0x03, //Illegal data values or ranges

OperationFail=0x04

}ModbusStatus;

4.1.3, Station Information Structure

/* Define the information used to access the slave station (server) */

typedef struct{

uint8_t UnitID;

  FunctionCode functionCode;

  uint16_t startingAddress;

  uint16_t quantity;

}ObjAccessInfo;

defines various information used to transmit access from a slave station (server), including station number, function code, starting address, and quantity.

4.1.4. Generate Access Slave PDU Unit Function

/* When used as an RTU master station (TCP client), generate commands for reading and writing RTU slave station (TCP server) objects */

uint16_t GenerateReadWriteCommand(ObjAccessInfo objInfo,bool *statusList,uint16_t *registerList,uint8_t commandBytes[]);

Parameters:ObjAccessInfo objInfo, the slave object to be accessed

boolean * statusList, the data list of the state quantity object to be written down

uint16ut * traderList, the data list of the register quantity object to be written down

uint8_t commandBytes[], Generated access commands

Return value:, in bytes.

4.1.5. Function for parsing the returned data read

/* parsing the data read by the master station (client) from the server */

void TransformClientReceptdData (uint8_t * acceptMessage, uint16ut quantity, boolean * statistList, uint16ut * registrant);

Parameters:uint8_t * receptidMessage, received information message

uint16ut quantity, number of read objects

boolean * statusList, parsed data list of read state objects

uint16ut * registrant, parsed data list of read register objects

Return value:

4.1.6. Response message function for generating read data command from slave station

/* Generate response for master station read access, including 0x01, 0x02, 0x03, 0x04 function codes, return The length of the corresponding information*/

uint16_t GenerateMasterAccessRespond(uint8_t *receivedMesasage,bool *statusList,uint16_t *registerList,uint8_t *respondBytes);

Parameters:uint8_t * acceptMesasage, received main battle read operation message

boolean * statusList, read slave station status object data list

uint16ut * traderList, read slave station register object data list

uint8_t * responsivBytes, generated slave station response message information

Return value:Response message length in bytes

4.1.7 Function code check function

/*Check if the function code is correct*/

ModbusStatus CheckFunctionCode(FunctionCode fc);

Parameters:FunctionCode fc, Function code, defined by enumeration

Return value:Modbus operation status, defined by enumeration

4.1.8, Generate TCP client command function

//Generate command for read-write server object

uint16ut Synthetic ReadWriteTCPServerCommand (ObjAccessInfo objInfo, boolean * statusList, uint16ut * registrant List, uint8_t * commandbytes);

Parameters:ObjAccessInfo objInfo, TCP server access information object

boolean * statusList, write server state quantity object data list

uint16ut * registrant List, write server register quantity object data list

uint8_t * commandbytes, generated command information message

Return value:The length of the command, in bytes

4.1.9. Generate TCP server response function

/* Synthesize response to server access */

uint16ut SynthesizeServer Access Response (uint8_t * acceptMesasage, boolean * statistList, uint16ut * registList, uint8_t * responsivByte);

Parameters:uint8_t * received Mesasage, received client command information message

boolean * statusList, read TCP server state quantity object data list

uint16_t *registerList, Read the register volume object data list of TCP server

uint8_t *respondBytes, The response information message generated in response to the client command

Return value:Response information message length in bytes

4.1.10, CRC check check

/* Check whether the received information is correct through CRC */

boolean CheckRTUMessageIntegrity (uint8_t * message, uint8_t length);

Parameters:uint8_t * message, data message to be verified

uint8_t length, data message length with instructions, in bytes

Return value:Returns the status signal of whether the verification has passed

Register List, uint8_t * Commandbytes);

/*Generate commands for reading and writing slave data objects, with a command length including 2 checksum bytes*/

uint16_t SyntheticReadWriteSlaveCommand(ObjAccessInfo slaveInfo,bool *statusList,uint16_t *registerList,uint8_t *commandBytes);

Parameter:ObjAccessInfo slaveInfo, access information object from the slave station, defined by the structure

bool *statusList, Write the slave status data list

uint16ut * tradeList, write the slave register data list

uint8_t * commandbytes, and generate the access command message

. Return value:The length of the access command, in bytes

4.1.12. Generate the slave response message function

/* Generate the slave response to the master station's response */

uint16ut Synthetic Slave Access Response (uint8_t * received Mesasage, boolean * statiusList, uint16ut * tradeList, uint13). 8_t * responders bytes);

Parameters:uint8_t * receivers Mesasage,

boolean * statistList,

uint16ut * registers List,

uint8_t * responsivbytes,

Return value:The length of the response information message generated, in bytes

4.1.13, LRC check function

/* to determine whether the ASCII data information is correct */

boolean CheckASCII Message Integrity (uint8_t * usMSG, uint16ut usLength)

Parameters:uint8_t * usMSG, list of messages to be verified, hexadecimal data

uint16ut usLength, list of messages to be verified Length

Return value:Check result, return "true" if checked correctly, return "false" if not

4.1.14 Convert ASCII message to hexadecimal

/* Convert received ASCII messages to hexadecimal */

boolean CovertAsciiMessageToHex (uint8_t * aMsg, uint8_t * hMsg, uint16ut aLen);

Parameters:uint8_t * aMsg, ASCII code information

uint8_t * hMsg, converted hexadecimal information

uint16ut aLun, length of ASCII code information

Return value:Whether the conversion is correct, returns "true" if the conversion is correct, otherwise returns "false"

4.1.15. Generate command function for reading and writing ASCII slave station

/* Generate commands for reading and writing slave station, applied to the master station, including checksum and start/end symbols */

uint16ut SyntheticReadWriteAscAsc iiSlaveCommand (ObjAccessInfo slaveInfo, boolean * statusList, uint16ut * registrant List, uint8_t * commandbytes)

Parameters:ObjAccessInfo slaveInfo, Accessing information objects from the slave station, defined by the structure

boolean * statistList, writing the slave station state data list

uint16ut * tradeList, writing the slave station register data list

uint8_t * commandbytes, generating the access command message

. Return value:length of the access command, in bytes

4.1.16. Generate ASCII slave station response to master station command function

/* Generate response to master station command, applied to slave stations */

uint16ut SynthicAsciiSlaveAccessRespond (uintRespond) 8_t * receptidMessage, boolean * statusList, uint16ut * registrant List, uint8_t * responsivByte)

Parameters:uint8_t * receptidMesasage, received message information from the main station

boolean * statusList, list of state values to be read by the main station command

uint16_t *registerList, The list of register values to be read by the master station command

uint8_t * responsiveBytes, the generated response information message

return value:The length of the generated response information message, in bytes

Chapter 3, Application Encapsulation Function

For application level encapsulation, we only encapsulate RTU master station applications, RTU slave station applications, TCP client applications, and TCP server-side applications.

4.2.1. RTU master and slave objects

/* Define the type of accessed RTU slave object */

typedef struct AccessedRTUSlaveType{

uint8_t stationAddress; //Station address

uint8_t cmdOrder; //The position of the current command in the command list

uint16ut commandNumber; //The total number of commands in the command list

uint8_t (*pReadCommand)[8]; //Read command list

  uint8_t *pLastCommand; //The last command sent was

uint32/t flagResetCoil; //Pre set coil control flag

uint322-t flagResetReg; //Pre register control flag bit

} RTUAccessdSlaveType;

/* Define local RTU master station object type */

typedef struct LocalRTUMasterType{

uint32_t flagWriteSlave[8]; //Write a station control flag, up to 256 stations, corresponding to the station address.

  uint16_t slaveNumber; //Number of slave stations in the slave station list

uint16_t readOrder; //The current position of the slave in the slave list

RTUAccessedSlaveType *pSlave; //From Station List

UpdateCoilStatusType pUpdateCoilStatus; //Update the coil quantity function

UpdateInputStatusType pUpdateInputStatus; //Update input state quantity function

UpdateHoldingRegisterType pUpdateHoldingRegister; //Update and maintain register quantity function

UpdateInputResgisterType pUpdateInputResgister; //Update input register quantity function

}RTULocalMasterType;

4.2.2. RTU Master Station Object Initialization Function

/*Initialize RTU master station object*/

void InitializeRTUMasterObject(RTULocalMasterType *master,uint16_t slaveNumber,RTUAccessedSlaveType *pSlave,UpdateCoilStatusType pUpdateCoilStatus,UpdateInputStatusType pUpdateInputStatus,UpdateHoldingRegisterType pUpdateHoldingRegister,UpdateInputResgisterType pUpdateInputResgister);

parameterRTULocalMasterType *master, Local main site object

uint16_t slaveNumber, Number of Stations

RTUAccessedSlaveType *pSlave, From Station List

UpdateCoilStatusType pUpdateCoilStatus, Update the coil quantity function pointer

UpdateInputStatusType pUpdateInputStatus, Update state variable function pointer

UpdateHoldingRegisterType pUpdateHoldingRegister, Update and maintain register quantity function pointer

UpdateInputResgisterType pUpdateInputResgister, Update input register quantity function pointer

Return value:No return value

4.2.3. Generate RTU master access slave command function

/*Generate commands to access the server*/

uint16_t CreateAccessSlaveCommand(ObjAccessInfo objInfo,void *dataList,uint8_t *commandBytes);

parameterObjAccessInfo objInfo, Accessing information objects from the site, defined by the structure

void *dataList, Write a data list for the slave object

uint8_t *commandBytes, Generated command message

Return value:The length of the generated access command, in bytes

4.2.4. RTU master station analyzes the response function of slave stations

/*Analyze the received server response information*/

void ParsingSlaveRespondMessage(uint8_t *recievedMessage,uint8_t *command);

parameteruint8_t *recievedMessage, Received return information

uint8_t *command, The command list that has been issued to the slave station

Return value:

4.2.5. RTU master station parsing slave station return message command matching function

/*After receiving the return information, determine whether it is the return information of the command in the sending command list*/

int FindCommandForRecievedMessage(uint8_t *recievedMessage,uint8_t (*commandList)[8],uint16_t commandNumber);

parameteruint8_t *recievedMessage, Received information returned by the slave station

uint8_t (*commandList)[8], List of commands issued by the main station

uint16_t commandNumber, The number of stored commands

Return value:Return the location of the matching command. If there is no match, return "-1"

This function is only used in the RTU master station when accessing large and frequent amounts of data, or when accessing multiple slave stations, to facilitate correct data parsing.

4.2.6. RTU slave station parsing master station access command function

/*Analyze the received information and return the synthesized reply message along with the byte length of the message, using a callback function*/

uint16_t ParsingMasterAccessCommand(uint8_t *receivedMesasage,uint8_t *respondBytes,uint16_t rxLength);

parameteruint8_t *receivedMesasage, Received message information from the main station

uint8_t *respondBytes, Generate response information message

uint16_t rxLength, The length of the received message

Return value:The length of the generated response information, in bytes

4.2.7 TCP Client Object and TCP Server Object

/*Define the type of TCP server object being accessed*/

typedef struct AccessedTCPServerType{

union {

uint32_t ipNumber;

uint8_t ipSegment[4];

}ipAddress; //The IP address of the server

uint32_t flagPresetServer; //Write server request flag

WritedCoilListHeadNode pWritedCoilHeadNode; //List of writable coil quantities

WritedRegisterListHeadNode pWritedRegisterHeadNode; //Writeable Keep Register List

struct AccessedTCPServerType *pNextNode; //Next TCP server node

}TCPAccessedServerType;

/*Define server chain header types*/

typedef struct ServerListHeadType {

TCPAccessedServerType *pServerNode; //Server node pointer

uint32_t serverNumber; //Number of servers

}ServerListHeadNode;

/*Define local TCP client object types*/

typedef struct LocalTCPClientType{

uint32_t transaction; //Transaction identifier

uint16_t cmdNumber; //Number of server commands read

uint16_t cmdOrder; //The current position of the slave in the slave list

uint8_t (*pReadCommand)[12]; //Read command list

ServerListHeadNode ServerHeadNode; //The head node of the Server object linked list

UpdateCoilStatusType pUpdateCoilStatus; //Update the coil quantity function

UpdateInputStatusType pUpdateInputStatus; //Update input state quantity function

UpdateHoldingRegisterType pUpdateHoldingRegister; //Update and maintain register quantity function

UpdateInputResgisterType pUpdateInputResgister; //Update input register quantity function

}TCPLocalClientType;

4.2.8. TCP Client Object Initialization Function

/*Initialize TCP client object*/

void InitializeTCPClientObject(TCPLocalClientType *client,uint16_t cmdNumber,uint8_t (*pReadCommand)[12],UpdateCoilStatusType pUpdateCoilStatus,UpdateInputStatusType pUpdateInputStatus,UpdateHoldingRegisterType pUpdateHoldingRegister,UpdateInputResgisterType pUpdateInputResgister);

parameterTCPLocalClientType *client, Client Object

uint16_t cmdNumber, Number of read commands

uint8_t (*pReadCommand)[12], Read command list

UpdateCoilStatusType pUpdateCoilStatus, Update the coil quantity function pointer

UpdateInputStatusType pUpdateInputStatus, Update state variable function pointer

UpdateHoldingRegisterType pUpdateHoldingRegister, Update and maintain register function pointers

UpdateInputResgisterType pUpdateInputResgister, Update input register quantity function pointer

Return value:No return value

4.2.9. Generate TCP Client Access Server Command Functions

/*Generate commands to access the server*/

uint16_t CreateAccessServerCommand(ObjAccessInfo objInfo,void *dataList,uint8_t *commandBytes);

parameterObjAccessInfo objInfo, Accessing server information objects

void *dataList, List of Server Object Data

uint8_t *commandBytes, Generated access server command message

Return value:Length of access command in bytes

4.2.10. TCP client parsing server return information function

/* parsing received server corresponding information */

void ParsingServerRespondMessage (uint8_t * recevedMessage);

Parameters:uint8_t * recevedMessage, received server response information

Return value:

4.2.11. TCP server parsing client command function

/* parses received information, returns the length of the response command */

uint16ut ParsingClientAccessCommand (uint8_t * received Message, uint8_t * responsiveBytes);

Parameters:uint8_t *receivedMessage, Received client access command

uint8_t * responsivBytes, generated server response information

Return value:The length of the generated response information message, in bytes

4.2.12 ASCII master and slave objects

/* Define the type of ASCII slave object being accessed */

typedef struct AccessedASCII SlaveType {

uint8_t stationAddress; //Station address

uint8_t cmdOrder; //The position of the current command in the command list

uint16ut commandNumber; //The total number of commands in the command list

uint8_t (*pReadCommand)[17]; //Read command list

uint8_t * pLastCommand; //Last command sent

  uint32_t flagPresetCoil; //Pre set coil control flag

uint322-t flagResetReg; //Pre register control flag bit

} AsciiAccesseSlaveType;

/* Define local ASCII master object type */

typedef struct LocalASCIIMasterType{

uint32_t flagWriteSlave[8]; //Write a station control flag, up to 256 stations, corresponding to the station address.

  uint16_t slaveNumber; //Number of slave stations in the slave station list

uint16ut readOrder; //The current position of the slave in the slave list

AsciiAccesseSlaveType * pSlave; //List of sites

Updating Coil Status Type pUpdating Coil Status; //Update coil quantity function

Updating Input Status Type pUpdating Input Status; //Update input state quantity function

Updating Holding Register Type pUpdating Holding Register; //Update and maintain register size function

Updating Input Register Type pUpdating Input Register; //Update input register quantity function

}AsciiLocalMasterType;

4.2.13. ASCII Master Object Initialization Function

/* Initialize RTU Master Object */

void Initialize ASCII Master Object (AsciiLocalMasterType * master, uint16ut slaveNumber, AsciiAccesseSlaveType * pSlave, Updating CovilStatus pUpdating CovilStatus, Updating InputStatus Type pUpdating InputStatus, Updating Holding Register Type pUpdating Holding Register, Updating InputRegister Type pUpdating InputRegister);

Parameters:AsciiLocalMasterType * master, ASCII master object

uint16ut slaveNumber, number of slave stations

AsciiAccesseSlaveType * pSlave, slave station list

Updating Coil Status type pUpdating Coil Status, update coil quantity callback function

Updating Input Status type pUpdating Input Status, update status quantity callback function

UpdateHoldingRegisterType pUpdateHoldingRegister, Update the callback function to maintain register volume

UpdateInputResgisterType pUpdateInputResgister, Update input register quantity callback function

Return value:No return value

4.2.14. Generate command to access ASCII slave

/* Generate command to access ASCII slave */

uint16ut CreateAccessAsciiSlaveCommand (ObjAccessInfo objInfo, void * dataList, uint8_t * commandbytes);

Parameters:ObjAccessInfo objInfo, access information object from the slave station, defined by the structure

void * dataList, write the data list of the slave station object

uint8_t * commandbytes, generated command message

Return value:The length of the access command generated, in bytes

4.2.15 ASCII response function of the master station parsing the slave station

/* parsing received server corresponding information */

void ParsingAsciiSlaveRespondMessage (uint8_t * recevedMessage, uint8_t * command, uint16ut rxLength);

Parameters:uint8_t * recevedMessage, received return message

uint8_t * command, command list that has been issued to the slave station

uint16ut rxLength, length of received message

Return value:

4.2.16 ASCII master station parsing slave station return message command matching function

/* After receiving the return message, determine whether it is the return message of the command in the send command list */

int FindAsciiCommandForRecievedMessage(uint8_t *recievedMessage,uint8_t (*commandList)[17],uint16_t commandNumber);

Parameter:uint8_t * recevedMessage, the received message returned by the slave station

uint8_t (*commandList)[17], List of commands issued by the main station

uint16ut commandNumber, number of stored commands

Return value:Return the location of the matching command. If there is no match, return "-1"

This function is only used in the RTU master station when accessing large and frequent amounts of data, or when accessing multiple slave stations, to facilitate correct data parsing.

4.2.17. ASCII Slave Station Parsing Master Station Access Command Function

/*Analyze the received information and return the synthesized reply message along with the byte length of the message, using a callback function*/

uint16_t ParsingAsciiMasterAccessCommand(uint8_t *receivedMessage, uint8_t *respondBytes, uint16_t rxLength, uint8_t StationAddress);

Parameters:uint8_t * acceptMesasage, received master station message information

uint8_t * responsivBytes, generates response information message

uint16ut rxLength, received message length

Return value:The length of the generated response information, in bytes

Chapter 4: Data Processing Functions

In specific applications, data processing is also involved, and different application data structures and processing methods vary greatly. Therefore, some callback functions (actually using the weakened function __weak keyword) are defined for data processing.

4.3.1. Function for Obtaining Coil Values

/*Get the value of the desired amount of Coil to be read*/

__weak void GetCoilStatus(uint16_t startAddress,uint16_t quantity,bool *statusList)

{

//If specific content needs to be implemented in Modbus TCP Server/RTU Slave applications

}

parameteruint16_t startAddress, To read the starting address of an object

uint16_t quantity, To read the number of objects

bool *statusList, List of data values obtained for coil quantity

Return value:

4.3.2. Function for obtaining input state values

/*Get the value of the InputStatus quantity you want to read*/

__weak void GetInputStatus(uint16_t startAddress,uint16_t quantity,bool *statusValue)

{

//If specific content needs to be implemented in Modbus TCP Server/RTU Slave applications

}

parameteruint16_t startAddress, To read the starting address of an object

uint16_t quantity, To read the number of objects

bool *statusValue, List of data values for the input state variables obtained

Return value:

4.3.3 Function for obtaining hold register values

/* Obtain the value of the hold register to be read*/

__weak void GetHoldingRegister(uint16_t startAddress,uint16_t quantity,uint16_t *registerValue)

{

//If specific content needs to be implemented in Modbus TCP Server/RTU Slave applications

}

Parameters:uint16ut startAddress, the starting address of the hold register object to be read

uint16ut quantity, the number of hold registers to be read

uint16ut * registrant Value, the value of the hold register to be obtained

Return value:

4.3.4. Function for obtaining input register value

/* Obtain the value of the input register to be read */

__weak void VNet InputRegister (uint16ut startAddress, uint16ut quantity) ty, uint16ut * tradeValue)

{

//If you need to implement it in Modbus TCP Server/RTU Slave applications, please refer to

}

. Parameters:uint16_t startAddress, The starting address of the input register to be read is

uint16ut quantity, the number of input registers to be read is

uint16ut * tradeValue, and the obtained value of the input register is

. Return value:

4.3.5. Set the value function for a single coil

/* Set the value for a single coil */

__weak void SetSingleCoil(uint16_t coilAddress,bool coilValue)

{

//If specific content needs to be implemented in Modbus TCP Server/RTU Slave applications

}

Parameters:uint16ut CoilAddress, the coil address for the preset value

boolean coilValue, the preset value

returns the value:

4.3.6, Function for setting the value of a single register

/* Set the value of a single register */

__weak void SettingleRegister (uint16ut registrant Address, uint16ut registrant Value)

{

//If specific content needs to be implemented in Modbus TCP Server/RTU Slave applications

}

parameteruint16ut registrant Address, pre-set hold register address

uint16ut registrant Value, pre-set hold register value

Return value:

4.3.7, Function for setting multiple coil values

/* Set multiple coil values */

__weak void SetMultipleCoil (uint16ut startAddress, uint16ut quantity, boolean * statisValue)

{

//If specific implementation is required in Modbus TCP Server/RTU Slave applications

}

parameteruint16_t startAddress, The starting addresses of multiple coils to be pre-set

uint16_t quantity, The number of coils to be predicted

bool *statusValue, List of coil values to be predicted

Return value:

4.3.8. Functions for Setting Multiple Register Values

/*Set the values of multiple registers*/

__weak void SetMultipleRegister(uint16_t startAddress,uint16_t quantity,uint16_t *registerValue)

{

//If specific content needs to be implemented in Modbus TCP Server/RTU Slave applications

}

Parameters:uint16ut startAddress, the starting address of multiple preset hold registers

uint16ut quantity, and the number of hold registers to be preset

uint16_t *registerValue, A list of predetermined register values to be maintained

Return value:

4.3.9. Function of coil values obtained from station updates

/*Update the coil status read back*/

__weak void UpdateCoilStatus(uint16_t startAddress,uint16_t quantity,bool *stateValue)

{

//Implement in the client (main station) application

}

parameteruint16_t startAddress, Starting address of the coil object for reading values

uint16_t quantity, The number of coils read

bool *stateValue, List of coil addresses read

Return value:

This program is the default processing function, and each main site object can define an update function separately. If it is not defined, this function will be called.

4.3.10, Function for obtaining input state values from station updates

/*Update the input status value read back*/

__weak void UpdateInputStatus(uint16_t startAddress,uint16_t quantity,bool *stateValue)

{

//Implement in the client (main station) application

}

parameteruint16_t startAddress, The starting address of the input state object read

uint16_t quantity, The number of input state objects read

bool *stateValue, The value of the input state object read

Return value:

This program is the default processing function, and each main site object can define an update function separately. If it is not defined, this function will be called.

4.3.11. Functions for updating and maintaining register values at the slave station

/*Update the read back hold register*/

__weak void UpdateHoldingRegister(uint16_t startAddress,uint16_t quantity,uint16_t *registerValue)

{

//Implement the

}

parameter in the client (main station) application:uint16ut startAddress, the starting address of the read hold register object

uint16ut quantity, the data of the read hold register object

uint16ut * registrant Value, and the value list of the read hold register object

. Return value:

This program is the default processing function, and each main station object can define an update function separately. If it is not defined, this function will be called.

4.3.12. Slave Station Update Input Register Value Function

/*Update the input register read back*/

__weak void UpdateInputResgister(uint16_t startAddress,uint16_t quantity,uint16_t *registerValue)

{

//Implement in the client (main station) application

}

parameteruint16_t startAddress, The starting address of the input register object read

uint16_t quantity, The number of input register objects read

uint16_t *registerValue, List of input register values read

Return value:

This program is the default processing function, and each main site object can define an update function separately. If it is not defined, this function will be called.

Chapter 5: Some Relevant Explanations

As for the entire development content of the Modbus protocol stack, it has been explained clearly earlier. Next, we will explain the content that is not directly related to development.

Firstly, regarding the question of why I developed this protocol stack. Our original intention was only to avoid rewriting this part every time we develop a product, but to continuously improve and use it to achieve the goal of reuse. Of course, later on, we felt that it was not just for ourselves to use, but also for anyone willing to use it publicly. The source code URL is: https://github.com/foxclever/Modbus

Secondly, the Modbus protocol has national standards, including three files. Our protocol stack is developed according to national standards, including the ability to read and write various types of object data, which is fully sufficient for general industrial applications. Three standard documents:

GB/T 19582.1-2008 "Industrial Automation Network Specification Based on Modbus Protocol Part 1: Modbus Application Protocol"

GB/T 19582.2-2008 "Industrial Automation Network Specification Based on Modbus Protocol Part 1: Implementation Guide for Modbus Protocol on Serial Link"

GB/T 19582.3-2008 "Industrial Automation Network Specification Based on Modbus Protocol Part 1: Implementation Guide of Modbus Protocol on TCP/IP"

Finally, we welcome everyone to use this protocol stack, but we are not responsible for the final results of use. Of course, if any shortcomings are found, we warmly welcome everyone to inform us of the issues discovered so that we can continue to improve.

Thank you for your attention to this software. If you need it, you can download it on GitHub. At the same time, you are welcome to give us suggestions for improvement. Interested colleagues can follow our official account:

Modbus protocol stack integrated instance parameter list
Station address: 1; Baud rate: 115200; Data bit: 8; Stop position: 1; No verification
Serial numberData typeVariable nameParameter nameAddressRead/write attributeValue rangeDefault ValueDescription
1uint32/tbeatTimeHeartbeat Detection40001Read OnlyIncrease once per second to monitor if the system is running properly
2floatmbAI1Analog Test40003Read OnlymbAO1 * 3
3floatmbAO1Analog Test40005read and write0~100.01.101
4uint16_tmbAI2Analog testing40007read-onlymbAO2*2
5uint16_tmbAO2Analog testing40008read and write0~1001Local variable
1floatmbSalve1AI1Target analog input parameter 1 from station 140009Read onlyTarget analog input parameter
2uint32/tmbSalve1AI2Target analog input parameter 2 from station 140011Read onlyTarget analog input parameter 1 from station 1
5uint16utmbSalve1AI3Analog input parameter 3 of target slave station 140013Read only0Analog output parameter 1 of target slave station 1
6uint16utmbSalve1AO1Read/write40014read and write101Analog output parameter 1 of target slave station 1
7uint16utmbSalve1AO2Analog output parameter 2 of target slave station 140015Read/write102Target station 1 simulation parameters
8uint16_tmbSalve1AO3Analog output parameter 3 of target slave station 140016read and write103Target station 1 simulation parameters
1floatmbSalve2AI1Analog input parameter 1 of target slave station 240017read-onlyTarget station 2 simulation parameters
2uint32_tmbSalve2AI2Analog input parameter 2 of target slave station 240019read-onlyTarget station 2 simulation parameters
5uint16_tmbSalve2AI3Analog input parameter 3 of target slave station 240021read-only0Target station 2 simulation parameters
6uint16_tmbSalve2AO1Analog output parameter 1 of target slave station 240022read and writeTarget station 2 simulation parameters
7uint16_tmbSalve2AO2Analog output parameter 2 of target slave station 240023read and write0Target station 2 simulation parameters
8uint16_tmbSalve2AO3Analog output parameter 3 of target slave station 240024read and write0Target station 2 simulation parameters
1floatmbSalve3AI1Analog input parameter 1 for target slave station 340025Read onlyAnalog input parameter 3 for target slave station 3
2uint32/tmbSalve3AI2Analog input parameter 2 for target slave station 340027Read onlyAnalog input parameter 3 for target slave station 3
5uint16utmbSalve3AI3Analog input parameter 3 for target slave station 340029Read only0Simulation parameters of target slave station 3
6uint16utmbSalve3AO1Simulation output parameters of target slave station 340030Read and writeSimulation parameters of target slave station 3
7uint16utmbSalve3AO2Simulation output parameters of target slave station 340031Read and write0Simulation parameters of target slave station 3
8uint16utmbSalve3AO3Analog output parameters of target slave station 340032Read and write0Analog input parameters of target slave station 3
1floatmbSalve4AI1Analog input parameters of target slave station 4 140033Read onlyAnalog input parameters of target slave station 4
2uint32/tmbSalve4AI2Analog input parameters of target slave station 4 240035Read onlyTarget Slave Station 4 Simulation Parameters
5uint16utmbSalve4AI3Target Slave Station 4 Analog Input Parameters 340037Read Only0Target Slave Station 4 Simulation Parameters
6uint16utmbSalve4AO1Target Slave Station 4 Analog Output Parameters 140038Read/WriteTarget Slave Station 4 Simulation Parameters
7uint16utmbSalve4AO2Target Slave Station 4 Analog Output Parameter 240039Read/Write0Target Slave Station 4 Analog Parameter
8uint16utmbSalve4AO3Target Slave Station 4 Analog Output Parameter 340040Read/Write0Target Slave Station 4 Analog Parameters
1boolmbDI1Digital Input Parameter 11Read OnlyNumerical parameter
2boolmbDI2Digital input parameter 22read-onlyNumerical parameter
3boolmbDI3Digital input parameter 33read-onlyNumerical parameter
4boolmbDI4Digital input parameter 44read-onlyDigital Parameters
5boolmbDO1Digital Output Parameters 15Read/WriteDigital Parameters
6boolmbDO2Digital Output Parameters 26Read/WriteDigital Parameters
7boolmbDO3Digital Output Parameters 37Read/WriteDigital Parameters
8boolmbDO4Digital Output Parameters 48Read/WriteDigital Parameters
1boolmbSalve1DI1Target Slave Station 1 Digital Input Parameters 19Read OnlyTarget Slave Station 1 Digital Parameters
2boolmbSalve1DI2Target Slave Station 1 Digital Input Parameters 210Read OnlyTarget slave station 1 digital quantity parameter
3boolmbSalve1DI3Target input parameter 3 for the numerical quantity of station 111read-onlyTarget slave station 1 digital quantity parameter
4boolmbSalve1DI4Target input parameter 4 for the numerical quantity of station 112read-onlyTarget slave station 1 digital quantity parameter
5boolmbSalve1DO1Target output parameter 1 of the digital quantity from station 113read and writeTarget Slave Station 1 Digital Quantity Parameter
6boolmbSalve1DO2Target Slave Station 1 Digital Quantity Output Parameter 214Read and WriteTarget Slave Station 1 Digital Quantity Parameter
7boolmbSalve1DO3Target output parameter 3 of digital quantity from station 115Read and WriteTarget slave station 1 digital quantity parameter
8boolmbSalve1DO4Target output parameter 4 of digital quantity from station 116read and writeTarget Slave Station 1 Digital Quantity Parameter
1boolmbSalve2DI1Target Slave Station 2 Digital Quantity Input Parameter 117Read OnlyTarget Slave Station 2 Digital Quantity Parameter
2boolmbSalve2DI2Target Slave Station 2 Digital Quantity Input Parameter 218Read OnlyTarget Slave Station 2 Digital Quantity Parameter
3boolmbSalve2DI3Target Slave Station 2 Digital Quantity Input Parameter 319Read OnlyTarget station 2 digital quantity parameter
4boolmbSalve2DI4Target input parameter 4 for the numerical quantity of station 220read-onlyTarget station 2 digital quantity parameter
5boolmbSalve2DO1Target output parameter 1 of the digital quantity from station 221read and writeTarget station 2 digital quantity parameter
6boolmbSalve2DO2Target output parameter 2 of the digital quantity from station 222read and writeTarget station 2 digital quantity parameter
7boolmbSalve2DO3Target output parameter 3 of digital quantity from station 223read and writeTarget station 2 digital quantity parameter
8boolmbSalve2DO4Target station 2's digital output parameter 424read and writeTarget station 2 digital quantity parameter
1boolmbSalve3DI1Target input parameter 1 for the numerical quantity of station 325read-onlyTarget station 3 digital quantity parameters
2boolmbSalve3DI2Target input parameter 2 for the numerical quantity of station 326read-onlyTarget station 3 digital quantity parameters
3boolmbSalve3DI3Target input parameter 3 for the numerical quantity of station 327read-onlyTarget station 3 digital quantity parameters
4boolmbSalve3DI4Target input parameter 4 for the numerical quantity of station 328read-onlyTarget station 3 digital quantity parameters
5boolmbSalve3DO1Target output parameter 1 of the digital quantity from station 329read and writeTarget station 3 digital quantity parameters
6boolmbSalve3DO2Target output parameter 2 of digital quantity from station 330read and writeTarget station 3 digital quantity parameters
7boolmbSalve3DO3Target output parameter 3 from station 331read and writeTarget station 3 digital quantity parameters
8boolmbSalve3DO4Target output parameter 4 of digital quantity from station 332read and writeTarget station 3 digital quantity parameters
1boolmbSalve4DI1Target input parameter 1 for the numerical quantity of station 433read-onlyTarget station 4 digital quantity parameters
2boolmbSalve4DI2Target input parameter 2 for the numerical quantity of station 434read-onlyTarget station 4 digital quantity parameters
3boolmbSalve4DI3Target input parameter 3 for the numerical quantity of station 435read-onlyTarget station 4 digital quantity parameters
4boolmbSalve4DI4Target input parameter 4 from station 436read-onlyTarget station 4 digital quantity parameters
5boolmbSalve4DO1Target output parameter 1 of digital quantity from station 437read and writeTarget Slave Station 4 Digital Quantity Parameter
6boolmbSalve4DO2Target Slave Station 4 Digital Quantity Output Parameter 238Read/WriteTarget Slave Station 4 Digital Quantity Parameter
7boolmbSalve4DO3Target Slave Station 4 Digital Quantity Output Parameter 339Read/WriteTarget Slave Station 4 Digital Quantity Parameter
8boolmbSalve4DO4Target Slave Station 4 Digital Quantity Output Parameter 440Read/WriteTarget Slave Station 4 Digital Quantity Parameter
Target Slave Station 1 Parameter List
Station address: 1; Baud rate: 9600; Data bit: 8; Stop position: 1; No verification
Serial numberdata typevariable nameparameter nameAddressRead and write propertiesValue rangedefault valueDescription
1floatmbSalve1AI1Analog input parameter 1 of target slave station 140001read-onlyTarget station 1 simulation parameters
2uint32_tmbSalve1AI2Target input parameter 2 of analog signal from station 140003read-onlyTarget station 1 simulation parameters
5uint16_tmbSalve1AI3Target input parameter 3 of analog signal from station 140005read-only0Target station 1 simulation parameters
6uint16_tmbSalve1AO1Analog output parameter 1 of target slave station 140006read and writeTarget station 1 simulation parameters
7uint16_tmbSalve1AO2Analog output parameter 2 of target slave station 140007read and write0Target station 1 simulation parameters
8uint16_tmbSalve1AO3Analog output parameter 3 of target slave station 140008read and write0Target station 1 simulation parameters
1boolmbSalve1DI1Target input parameter 1 for the numerical quantity of station 11read-onlyTarget slave station 1 digital quantity parameter
2boolmbSalve1DI2Target input parameter 2 for the numerical quantity of station 12read-onlyTarget slave station 1 digital quantity parameter
3boolmbSalve1DI3Target input parameter 3 for the numerical quantity of station 13read-onlyTarget slave station 1 digital quantity parameter
4boolmbSalve1DI4Target input parameter 4 for the numerical quantity of station 14read-onlyTarget slave station 1 digital quantity parameter
5boolmbSalve1DO1Target output parameter 1 of the digital quantity from station 15read and writeTarget slave station 1 digital quantity parameter
6boolmbSalve1DO2Target output parameter 2 of digital quantity from station 16read and writeTarget slave station 1 digital quantity parameter
7boolmbSalve1DO3Target output parameter 3 of digital quantity from station 17read and writeTarget slave station 1 digital quantity parameter
8boolmbSalve1DO4Target output parameter 4 of digital quantity from station 18read and writeTarget Slave Station 1 Digital Quantity Parameter
Target Slave Station 2 Parameter List
Station address: 2; Baud rate: 9600; Data bit: 8; Stop position: 1; No verification
Serial numberdata typevariable nameparameter nameAddressRead and write propertiesValue rangedefault valueDescription
1floatmbSalve2AI1Analog input parameter 1 for target slave station 240001Read onlyAnalog input parameter 2 for target slave station 2
2uint32_tmbSalve2AI2Analog input parameter 2 of target slave station 240003read-onlyTarget station 2 simulation parameters
5uint16_tmbSalve2AI3Analog input parameter 3 of target slave station 240005Read only0Target slave station 2 simulation parameters
6uint16utmbSalve2AO1Target slave station 2 analog output parameter 140006Read and writeTarget slave station 2 simulation parameters
7uint16utmbSalve2AO2Target slave station 2 analog output parameter 240007Read and write0Target slave station 2 simulation parameters
8uint16_tmbSalve2AO3Analog output parameter 3 of target slave station 240008read and write0Target station 2 simulation parameters
1boolmbSalve2DI1Target input parameter 1 for the numerical quantity of station 21read-onlyTarget station 2 digital quantity parameter
2boolmbSalve2DI2Target input parameter 2 for the numerical quantity of station 22read-onlyTarget station 2 digital quantity parameter
3boolmbSalve2DI3Target input parameter 3 for the numerical quantity of station 23read-onlyTarget station 2 digital quantity parameter
4boolmbSalve2DI4Target input parameter 4 for the numerical quantity of station 24read-onlyTarget station 2 digital quantity parameter
5boolmbSalve2DO1Target output parameter 1 of the digital quantity from station 25read and writeTarget station 2 digital quantity parameter
6boolmbSalve2DO2Target output parameter 2 of the digital quantity from station 26read and writeTarget station 2 digital quantity parameter
7boolmbSalve2DO3Target output parameter 3 of digital quantity from station 27read and writeTarget station 2 digital quantity parameter
8boolmbSalve2DO4Target station 2's digital output parameter 48read and writeTarget Slave Station 2 Digital Parameter
Target Slave Station 1 Parameter List
Station address: 3; Baud rate: 9600; Data bit: 8; Stop position: 1; No verification
Serial numberdata typevariable nameparameter nameAddressRead and write propertiesValue rangedefault valueDescription
1floatmbSalve3AI1Analog input parameter 1 of target slave station 340001read-onlyTarget station 3 simulation parameters
2uint32_tmbSalve3AI2Analog input parameter 2 of target slave station 340003read-onlyTarget station 3 simulation parameters
5uint16_tmbSalve3AI3Analog input parameter 3 of target slave station 340005read-only0Target station 3 simulation parameters
6uint16_tmbSalve3AO1Analog output parameter 1 of target slave station 340006read and writeTarget station 3 simulation parameters
7uint16_tmbSalve3AO2Analog output parameter 2 of target slave station 340007read and write0Target station 3 simulation parameters
8uint16_tmbSalve3AO3Analog output parameter 3 of target slave station 340008read and write0Target station 3 simulation parameters
1boolmbSalve3DI1Target input parameter 1 for the numerical quantity of station 31read-onlyTarget station 3 digital quantity parameters
2boolmbSalve3DI2Target input parameter 2 for the numerical quantity of station 32read-onlymbSalve3DI3
3boolmbSalve3DI3Target Slave Station 3 Digital Quantity Input Parameter 33Read OnlyTarget Slave Station 3 Digital Quantity Parameter
4boolmbSalve3DI4Target Slave Station 3 Digital Quantity Input Parameter 44Read OnlyTarget Slave Station 3 Digital Quantity Parameter
5boolmbSalve3DO1Target Slave Station 3 Digital Quantity Output Parameter 15read and writeTarget Slave Station 3 Digital Quantity Parameter
6boolmbSalve3DO2Target Slave Station 3 Digital Quantity Output Parameter 26Read/WriteTarget Slave Station 3 Digital Quantity Parameter
7boolmbSalve3DO3Target Slave Station 3 Digital Quantity Output Parameter 37Read/WriteTarget Slave Station 3 Digital Quantity Parameter
8boolmbSalve3DO4Target Slave Station 3 Digital Quantity Output Parameter 48Read/WriteTarget Slave Station 3 Digital Parameter
Target Slave Station 1 Parameter List
Station Address: 4; Baud rate: 9600; Data bit: 8; Stop position: 1; No verification
Serial numberData typeVariable nameParameter nameAddressRead/write propertiesValue rangeDefault valueDescription
1floatmbSalve4AI1Analog input parameter 1 for target slave station 440001Read onlyAnalog input parameter 2 for target slave station 4
2uint32_tmbSalve4AI2Target input parameter 2 of analog signal from station 440003read-onlyAnalog input parameter 3 for target slave station 4
5uint16utmbSalve4AI3Target input parameter 3 of analog signal from station 440005Read only0Target slave station 4 simulation parameters
6uint16utmbSalve4AO1Target slave station 4 analog output parameter 140006Read and writeTarget slave station 4 simulation parameters
7uint16utmbSalve4AO2Target slave station 4 analog output parameter 240007Read and write0Target slave station 4 simulation parameters
8uint16utmbSalve4AO3Analog output parameter 3 of target slave station 440008Read and write0Analog input parameter 1 of target slave station 4
1boolmbSalve4DI1Read only1read-onlyDigital input parameter 2 of target slave station 4
2boolmbSalve4DI2Read only2read-onlyTarget Slave Station 4 Digital Quantity Parameter
3boolmbSalve4DI3Target Slave Station 4 Digital Quantity Input Parameter 33Read OnlyTarget Slave Station 4 Digital Quantity Parameter
4boolmbSalve4DI4Target Slave Station 4 Digital Quantity Input Parameter 44Read OnlyTarget Slave Station 4 Digital Quantity Parameter
5boolmbSalve4DO1Target Slave Station 4 Digital Quantity Output Parameter 15Read/WriteTarget Slave Station 4 Digital Quantity Parameter
6boolmbSalve4DO2Target Slave Station 4 Digital Quantity Output Parameter 26Read and WriteTarget Slave Station 4 Digital Quantity Parameter
7boolmbSalve4DO3Target Slave Station 4 Digital Quantity Output Parameter 37Read and WriteTarget Slave Station 4 Digital Quantity Parameter
8boolmbSalve4DO4Target Slave Station 4 Digital Quantity Output Parameter 48Read and WriteTarget Slave Station 4 Digital Quantity Parameters
Put this resource to use in a real project?

Go to the Tool Center for message parsing, CRC verification and device debugging, or submit your requirements for selection and integration advice.

Engineer Membership

Turn this article into actionable debugging resources

After activation, you can use advanced message parsing, resource pack downloads, code examples, engineering cases and priority technical support, suitable for real project delivery.

Unlimited Advanced Tools
Resource & Code Packs
Complete Engineering Case Library
Priority Technical Support

Leave a Reply

Your email address will not be published. Required fields are marked *.