程序部分:
/*******************************************************************************
** 名 称 : ModbusRTUCommunication
** 功 能 : 分析ModbusRTU命令,并返回ModbusRTU数据
** 入口参数 : 无
** 出口参数 : 无
*******************************************************************************/
void ModbusRTUCommunication()
{
unsigned char cy_q,cy_s;
if(cy_receive_buf[0] == 1) //判断从机地址
{
start_crc_chec(); //crc校验
if((crc_chec.bytes.hi==cy_receive_buf[cy_uartnumber-1])&&(crc_chec.bytes.lo==cy_receive_buf[cy_uartnumber-2])) //判断校验码
{
VICIntEnable &= ( !(1u << 0x06) ); //关中断
switch(cy_receive_buf[1])
{
case 3://读寄存器
/*地址分析 2/3字节为起始地址 4/5字节为寄存器个数 最多读15个寄存器(15*2*8位) */
if((cy_receive_buf[2]==0)&&(cy_receive_buf[4]==0)&&((cy_receive_buf[3]+cy_receive_buf[5])<=14)) ////地址分析 2/3字节为起始地址 4/5字节为寄存器个数
{
cy_receive_buf[2]=cy_receive_buf[5]*2; // 响应字节数=寄存器个数*2
cy_uartnumber=3; // 字节起始地址
cy_q=cy_receive_buf[3]+cy_receive_buf[5]; //最大字节地址
/*从机响应*/
for(cy_s=cy_receive_buf[3];cy_s<cy_q;cy_s++)
{
cy_receive_buf[cy_uartnumber]=(V[cy_s]&0xFF00)>>8;
cy_uartnumber++;
cy_receive_buf[cy_uartnumber]=V[cy_s]&0x00FF;
cy_uartnumber++;
}
generic_crc(cy_uartnumber);
cy_uartnumber=cy_uartnumber+2;
frame_send(cy_uartnumber);//发送数据
}
break;
case 6://写单个寄存器
if((cy_receive_buf[2]==0)&&(cy_receive_buf[3]<=14)) //地址分析
{
V[cy_receive_buf[3]]=cy_receive_buf[4]*0x100+cy_receive_buf[5];//更改指定数据
frame_send(cy_uartnumber);//发送数据
}
break;
default:
break;
}
VICIntEnable = 1u << 0x06; //开中断
}
}
cy_uartnumber = 0;
}
|