近项目有用到modbus协议,于是在网上找了些资料成功将freemodbus移植到m3,由于移植过程较简单,网上教程也很多,这里我们就不再赘述.我用到的freemodbus版本是V1.5,下面附上新的源码下载地址:http://www.freemodbus.org/index.php?idx=5
下面开始分析下freemodbus得启动流程,老规矩我们还是从main()函数下手:
和freemodbus有关的函数只有三个eMBInit(), eMBEnable(), eMBPoll().我们逐一来分析.
首先是eMBInit(),我们来看下源码:eMBErrorCode
eMBInit( eMBMode eMode, UCHAR ucSlaveAddress, UCHAR ucPort,
ULONG ulBaudRate, eMBParity eParity )
{
//错误状态初始值
eMBErrorCode eStatus = MB_ENOERR;
//验证从机地址
if( ( ucSlaveAddress == MB_ADDRESS_BROADCAST ) ||
( ucSlaveAddress < MB_ADDRESS_MIN ) ||
( ucSlaveAddress > MB_ADDRESS_MAX ) )
{
eStatus = MB_EINVAL;
}
else
{
ucMBAddress = ucSlaveAddress;
switch ( eMode )
{
#if MB_RTU_ENABLED > 0
case MB_RTU:
pvMBFrameStartCur = eMBRTUStart;
pvMBFrameStopCur = eMBRTUStop;
peMBFrameSendCur = eMBRTUSend;
//报文接收函数
peMBFrameReceiveCur = eMBRTUReceive;
pvMBFrameCloseCur = MB_PORT_HAS_CLOSE ? vMBPortClose : NULL;
//接收状态机
pxMBFrameCBByteReceived = xMBRTUReceiveFSM;
//发送状态机
pxMBFrameCBTransmitterEmpty = xMBRTUTransmitFSM;
//报文到达间隔检查
pxMBPortCBTimerExpired = xMBRTUTimerT35Expired;
//初始化RTU
eStatus = eMBRTUInit( ucMBAddress, ucPort, ulBaudRate, eParity );
break;
#endif
#if MB_ASCII_ENABLED > 0
case MB_ASCII:
pvMBFrameStartCur = eMBASCIIStart;
pvMBFrameStopCur = eMBASCIIStop;
peMBFrameSendCur = eMBASCIISend;
peMBFrameReceiveCur = eMBASCIIReceive;
pvMBFrameCloseCur = MB_PORT_HAS_CLOSE ? vMBPortClose : NULL;
pxMBFrameCBByteReceived = xMBASCIIReceiveFSM;
pxMBFrameCBTransmitterEmpty = xMBASCIITransmitFSM;
pxMBPortCBTimerExpired = xMBASCIITimerT1SExpired;
eStatus = eMBASCIIInit( ucMBAddress, ucPort, ulBaudRate, eParity );
break;
#endif
default:
eStatus = MB_EINVAL;
}
//
if( eStatus == MB_ENOERR )
{
if( !xMBPortEventInit() )
{
/* port dependent event module initalization failed. */
eStatus = MB_EPORTERR;
}
else
{
//设定当前状态
eMBCurrentMode = eMode;
eMBState = STATE_DISABLED;