本文为modbus代码讲解概述,实现modbus具体操作请点击以下博客:
基于STM32F767通过STM32CubeMX实现ModbusTCP从站(后续)
(1)stm32f767开发板,下载安装STM32CubeMX;
(2)实现LWIP的引入,具体参考STM32cubeMX将STM32F767+LAN8720+LwIP+FreeRTOS的以太网实现确保可以PING通;
(3)下载ModbusTCP包,附上楼主现有包链接:https://pan.baidu.com/s/1G2MblV6BSW2OHU62038B1g
提取码:53os ;
按照一下方式加入文件(大神可按自己的习惯操作)
文件导入后不要忘记加入相应头文件:点击魔法棒 > 进入C/C++选项卡,点击Include Paths后的 … 按钮,将下图的Modbus相关目录加入
本次主要讲读保持寄存器功能,所以主要解释的文件为上图middlewares/Modbus目录下的mbfuncholding.c文件,以下附上该文件代码
/* ----------------------- System includes ----------------------------------*/
#include "stdlib.h"
#include "string.h"
/* ----------------------- Platform includes --------------------------------*/
#include "port.h"
/* ----------------------- Modbus includes ----------------------------------*/
#include "mb.h"
#include "mbframe.h"
#include "mbproto.h"
#include "mbconfig.h"
/* ----------------------- Defines ------------------------------------------*/
#define MB_PDU_FUNC_READ_ADDR_OFF ( MB_PDU_DATA_OFF + 0)
#define MB_PDU_FUNC_READ_REGCNT_OFF ( MB_PDU_DATA_OFF + 2 )
#define MB_PDU_FUNC_READ_SIZE ( 4 )
#define MB_PDU_FUNC_READ_REGCNT_MAX ( 0x007D )
#define MB_PDU_FUNC_WRITE_ADDR_OFF ( MB_PDU_DATA_OFF + 0)
#define MB_PDU_FUNC_WRITE_VALUE_OFF ( MB_PDU_DATA_OFF + 2 )
#define MB_PDU_FUNC_WRITE_SIZE ( 4 )
#define MB_PDU_FUNC_WRITE_MUL_ADDR_OFF ( MB_PDU_DATA_OFF + 0 )
#define MB_PDU_FUNC_WRITE_MUL_REGCNT_OFF ( MB_PDU_DATA_OFF + 2 )
#define MB_PDU_FUNC_WRITE_MUL_BYTECNT_OFF ( MB_PDU_DATA_OFF + 4 )
#define MB_PDU_FUNC_WRITE_MUL_VALUES_OFF ( MB_PDU_DATA_OFF + 5 )
#define MB_PDU_FUNC_WRITE_MUL_SIZE_MIN ( 5 )
#define MB_PDU_FUNC_WRITE_MUL_REGCNT_MAX ( 0x0078 )
#define MB_PDU_FUNC_READWRITE_READ_ADDR_OFF ( MB_PDU_DATA_OFF + 0 )
#define MB_PDU_FUNC_READWRITE_READ_REGCNT_OFF ( MB_PDU_DATA_OFF + 2 )
#define MB_PDU_FUNC_READWRITE_WRITE_ADDR_OFF ( MB_PDU_DATA_OFF + 4 )
#define MB_PDU_FUNC_READWRITE_WRITE_REGCNT_OFF ( MB_PDU_DATA_OFF + 6 )
#define MB_PDU_FUNC_READWRITE_BYTECNT_OFF ( MB_PDU_DATA_OFF + 8 )
#define MB_PDU_FUNC_READWRITE_WRITE_VALUES_OFF ( MB_PDU_DATA_OFF + 9 )
#define MB_PDU_FUNC_READWRITE_SIZE_MIN ( 9 )
/* ----------------------- Static functions ---------------------------------*/
eMBException prveMBError2Exception( eMBErrorCode eErrorCode );
/* ----------------------- Start implementation -----------------------------*/
以上为ModbusTCP关于操作保持寄存器对收到代码的对应位置的代码作用记录;
#if MB_FUNC_WRITE_HOLDING_ENABLED > 0
eMBException
eMBFuncWriteHoldingRegister( UCHAR * pucFrame, USHORT * usLen )
{
USHORT usRegAddress;
eMBException eStatus = MB_EX_NONE;
eMBErrorCode eRegStatus;
if( *usLen == ( MB_PDU_FUNC_WRITE_SIZE + MB_PDU_SIZE_MIN ) )
{
usRegAddress = ( USHORT )( pucFrame[MB_PDU_FUNC_WRITE_ADDR_OFF] << 8 );
usRegAddress |= ( USHORT )( pucFrame[MB_PDU_FUNC_WRITE_ADDR_OFF + 1] );
usRegAddress++;
/* Make callback to update the value. */
eRegStatus = eMBRegHoldingCB( &pucFrame[MB_PDU_FUNC_WRITE_VALUE_OFF],
usRegAddress, 1, MB_REG_WRITE );
/* If an error occured convert it into a Modbus exception. */
if( eRegStatus != MB_ENOERR )
{
eStatus = prveMBError2Exception( eRegStatus );
}
}
else
{
/* Can't be a valid request because the length is incorrect. */
eStatus = MB_EX_ILLEGAL_DATA_VALUE;
}
return eStatus;
}
#endif
该段是写一位保持寄存器的具体代码;
#if MB_FUNC_WRITE_MULTIPLE_HOLDING_ENABLED > 0
eMBException
eMBFuncWriteMultipleHoldingRegister( UCHAR * pucFrame, USHORT * usLen )
{
USHORT usRegAddress;
USHORT usRegCount;
UCHAR ucRegByteCount;
eMBException eStatus = MB_EX_NONE;
eMBErrorCode eRegStatus;
if( *usLen >= ( MB_PDU_FUNC_WRITE_MUL_SIZE_MIN + MB_PDU_SIZE_MIN ) )
{
usRegAddress = ( USHORT )( pucFrame[MB_PDU_FUNC_WRITE_MUL_ADDR_OFF] << 8 );
usRegAddress |= ( USHORT )( pucFrame[MB_PDU_FUNC_WRITE_MUL_ADDR_OFF + 1] );
usRegAddress++;
usRegCount = ( USHORT )( pucFrame[MB_PDU_FUNC_WRITE_MUL_REGCNT_OFF] << 8 );
usRegCount |= ( USHORT )( pucFrame[MB_PDU_FUNC_WRITE_MUL_REGCNT_OFF + 1] );
ucRegByteCount = pucFrame[MB_PDU_FUNC_WRITE_MUL_BYTECNT_OFF];
if( ( usRegCount >= 1 ) &&
( usRegCount <= MB_PDU_FUNC_WRITE_MUL_REGCNT_MAX ) &&
( ucRegByteCount == ( UCHAR ) ( 2 * usRegCount ) ) )
{
/* Make callback to update the register values. */
eRegStatus =
eMBRegHoldingCB( &pucFrame[MB_PDU_FUNC_WRITE_MUL_VALUES_OFF],
usRegAddress, usRegCount, MB_REG_WRITE );
/* If an error occured convert it into a Modbus exception. */
if( eRegStatus != MB_ENOERR )
{
eStatus = prveMBError2Exception( eRegStatus );
}
else
{
/* The response contains the function code, the starting
* address and the quantity of registers. We reuse the
* old values in the buffer because they are still valid.
*/
*usLen = MB_PDU_FUNC_WRITE_MUL_BYTECNT_OFF;
}
}
else
{
eStatus = MB_EX_ILLEGAL_DATA_VALUE;
}
}
else
{
/* Can't be a valid request because the length is incorrect. */
eStatus = MB_EX_ILLEGAL_DATA_VALUE;
}
return eStatus;
}
#endif
由于ModbusTCP是以TCP协议为基础的Modbus协议,所以接收到的数据是以TCP协议包内嵌Modbus协议包来完成的,所以就需要对包进行分层解析,首先解析了TCP层相应数据后再解析Modbus层数据,所以首先我们的代码中会有一段建立TCP服务器的代码,其代码在middlewares/Modbus/port目录下的porttcp.c文件,代码如下
xMBTCPPortInit( USHORT usTCPPort )
{
struct tcp_pcb *pxPCBListenNew, *pxPCBListenOld;
BOOL bOkay = FALSE;
USHORT usPort;
if( usTCPPort == 0 )
{
usPort = MB_TCP_DEFAULT_PORT;
}
else
{
usPort = ( USHORT ) usTCPPort;
}
if( ( pxPCBListenNew = pxPCBListenOld = tcp_new( ) ) == NULL ) //建立TCP服务器
{
/* Can't create TCP socket. */
bOkay = FALSE;
}
else if( tcp_bind( pxPCBListenNew, IP_ADDR_ANY, ( u16_t ) usPort ) != ERR_OK )//TCP服务器建立成功后进入监听状态
{
/* Bind failed - Maybe illegal port value or in use. */
( void )tcp_close( pxPCBListenOld );
bOkay = FALSE;
}
else if( ( pxPCBListenNew = tcp_listen( pxPCBListenNew ) ) == NULL )
{
( void )tcp_close( pxPCBListenOld );
bOkay = FALSE;
}
else
{
/* Register callback function for new clients. */
tcp_accept( pxPCBListenNew, prvxMBTCPPortAccept );
/* Everything okay. Set global variable. */
pxPCBListen = pxPCBListenNew;
#ifdef MB_TCP_DEBUG
vMBPortLog( MB_LOG_DEBUG, "MBTCP-ACCEPT", "Protocol stack ready.\r\n" );
#endif
}
bOkay = TRUE;
return bOkay;
}
以上代码为TCP服务器的建立过程,ModbusTCP默认端口为502端口,此处无需更改;
以上讲述了ModbusTCP从建立TCP服务器到对收到的代码进行解析的过程,接下来就要进行收到数据的操作过程,其代码位于middlewares/Modbus目录下的modbusCB.c文件中,代码如下
uint16_t DB_R[88]; //保持寄存器数值存储空间
uint16_t DB_C[88]; //线圈寄存器数值存储空间
uint16_t DB_I[88]; //输入流数值存储空间
uint16_t DB_D[88]; //离散量数值存储空间
eMBErrorCode
eMBRegHoldingCB( UCHAR * pucRegBuffer, USHORT usAddress, USHORT usNRegs, eMBRegisterMode eMode )
{
eMBErrorCode eStatus = MB_ENOERR;
static uint8_t flag = 0;
int i=0;
flag ^= 1;
/*the following code is just for the testing the function of reading register */
/**********************************读保持寄存器************************************/
if(eMode==MB_REG_READ)
{
DB_R[0]=0x1001;
DB_R[1]=0x2001;
DB_R[2]=0x3001;
DB_R[3]=0x4001;
for(i=0;i>8;
pucRegBuffer++;
*pucRegBuffer=DB_R[i+usAddress-1]&0xff;
pucRegBuffer++;
}
}
/***************************************GAS********************************************/
/*********************************写保持寄存器*************************************/
if(eMode==MB_REG_WRITE)
{
for(i=0;i>8;
pucRegBuffer++;
DB_R[i+usAddress-1]=*pucRegBuffer&0xff;
pucRegBuffer++;
}
}
/**************************************GAS*****************************************/
return eStatus;
}
上述代码主要功能在读写保持寄存器,开辟了4个存储空间用于存放保持寄存器数值、线圈寄存器数值、输入量数值和离散量数值,为测试通讯正常,我提前将数值写入保持寄存器数值存储空间的0~3空间分别写入值,方便读取。由于代码没有完全写明白,所以在写保持寄存器时只能写入第8位,无法写入高8位,希望有经验的大能不吝赐教。
在上述操作完成后,在主函数中加入:
eMBTCPInit( 0 );
eMBEnable();
之后再主函数的主循环加入:
eMBPoll();
即可不断运行Modbus的数据操作。
在上述文件导入工程后编译下载到开发板,用网线连接开发版和计算机。在计算机下载安装ModbusTool工具(可在GITHUB上搜索下载),该代码实现的时从站(服务器)功能,所以打开ModbusTool工具的MBMaster (Active),在确保可以ping通开发板的情况下按照下图所示设置,IP写为开发板地址,设置完成后点击Connect,在下方黑框提示连接成功即可;若链接失败,检查网络情况或重启开发板;
完成连接后点击Read holding即可在0~3所在空格读取到之前设置在DB_R数组中的值,如图
完成以上操作后说明ModbusTCP协议已打通,也可以读取到Modbus数据,接下来的工作就是通过接收到的数据控制硬件动作,由大家自由发挥,希望大家能多多指点。