二、代码修改
1.首先在主函数中调用初始化函数并且使能modbus:
eMBMasterInit(MB_RTU, 2, 115200, MB_PAR_EVEN);
eMBMasterEnable();
2.在一个大循环中调用eMBMasterPoll。
三、操作从机
usModbusUserData[0] = (USHORT)(rt_tick_get()/10);
usModbusUserData[1] = (USHORT)(rt_tick_get()%10);
errorCode = eMBMasterReqWriteHoldingRegister(1,3,usModbusUserData[0],200);
// errorCode = eMBMasterReqReadHoldingRegister(1,3,1,RT_WAITING_FOREVER);
// errorCode = eMBMasterReqWriteCoil(1,8,0xFF00,RT_WAITING_FOREVER);
if (errorCode != MB_MRE_NO_ERR)
{
errorCount++;
rt_kprintf("error\n");
}
else
rt_kprintf("no error\n");
读取出来的数据在这几个数组中
/*-----------------------Master mode use these variables----------------------*/
#if MB_MASTER_RTU_ENABLED > 0 || MB_MASTER_ASCII_ENABLED > 0
//Master mode:DiscreteInputs variables
USHORT usMDiscInStart = M_DISCRETE_INPUT_START;
#if M_DISCRETE_INPUT_NDISCRETES%8
UCHAR ucMDiscInBuf[MB_MASTER_TOTAL_SLAVE_NUM][M_DISCRETE_INPUT_NDISCRETES/8+1];
#else
UCHAR ucMDiscInBuf[MB_MASTER_TOTAL_SLAVE_NUM][M_DISCRETE_INPUT_NDISCRETES/8];
#endif
//Master mode:Coils variables
USHORT usMCoilStart = M_COIL_START;
#if M_COIL_NCOILS%8
UCHAR ucMCoilBuf[MB_MASTER_TOTAL_SLAVE_NUM][M_COIL_NCOILS/8+1];
#else
UCHAR ucMCoilBuf[MB_MASTER_TOTAL_SLAVE_NUM][M_COIL_NCOILS/8];
#endif
//Master mode:InputRegister variables
USHORT usMRegInStart = M_REG_INPUT_START;
USHORT usMRegInBuf[MB_MASTER_TOTAL_SLAVE_NUM][M_REG_INPUT_NREGS];
//Master mode:HoldingRegister variables
USHORT usMRegHoldStart = M_REG_HOLDING_START;
USHORT usMRegHoldBuf[MB_MASTER_TOTAL_SLAVE_NUM][M_REG_HOLDING_NREGS];
|