|
![](static/image/common/ico_lz.png)
楼主 |
发表于 2008-1-24 09:13:02
|
显示全部楼层
最近仔细看了MODBUS协议,发现该函数的错误应答的数据有点问题,就改了一下,可能也不是很完善,但可以肯定比上面的要正确(相对来说),请AMORK给更新一下吧
声明:仅下面这两个函数是我在本网站上的相关资料改的,如又异议,通知我,我删除
void Com0_Communication(void)
{
unsigned short crcresult;
unsigned char temp[2];
crcresult= getCRC16(Com0_Receive_Data_Buffer,Com0_Receive_CRCcouter-2);
temp[1]=crcresult & 0xff;
temp[0]=(crcresult >> 8) & 0xff;
if((Com0_Receive_Data_Buffer[Com0_Receive_CRCcouter-1]==temp[0])&&(Com0_Receive_Data_Buffer[Com0_Receive_CRCcouter-2]==temp[1]))
{
switch(Com0_Receive_Data_Buffer[1])
{
case 0x01:
Modbus_Function_1();
break;
case 0x03:
Modbus_Function_3();
break;
case 0x05:
Modbus_Function_5();
break;
case 0x02:
Modbus_Function_2();
break;
case 0x10:
Modbus_Function_16();
break;
default:
{
Com0_Send_Data_Buffer[1]=Com0_Receive_Data_Buffer[1]+0x80;
Com0_Send_Data_Buffer[2]=1;
Com0_Send_Data_Bytes=3;
}
}
}
else
{
////show error!
Com0_Send_Data_Buffer[1]=0xFF;
Com0_Send_Data_Buffer[2]=3;
Com0_Send_Data_Bytes=5;
}
crcresult= getCRC16(Com0_Send_Data_Buffer,Com0_Send_Data_Bytes);
Com0_Send_Data_Buffer[Com0_Send_Data_Bytes]=crcresult & 0xff;
Com0_Send_Data_Buffer[Com0_Send_Data_Bytes+1]=(crcresult >> 8) & 0xff;
Com0_Send_Data_Bytes=Com0_Send_Data_Bytes+2;
Com0_Send_Data_Pointer=Com0_Send_Data_Buffer;
UDR0=*Com0_Send_Data_Pointer;
}
这个功能是读线圈的状态的,给大家看一下,这样就能运行了,并且能够通过MODBUS调试软件调试了,可以说是一个最小的系统了吧
有问题在这里留言
void Modbus_Function_1(void)
{
unsigned char a, b,c,i;
unsigned int temp;
Com0_Send_Data_Buffer[1]=0x01;
if((Com0_Receive_Data_Buffer[4]==0)&&(Com0_Receive_Data_Buffer[5]<6))
{
if((Com0_Receive_Data_Buffer[2]==0)&&(Com0_Receive_Data_Buffer[3]<6)&&((Com0_Receive_Data_Buffer[3]+Com0_Receive_Data_Buffer[5])<6 ))
{
a=Com0_Receive_Data_Buffer[3]>>3; //¿ªÊ¼µØÖ·³ýÒÔ8
b=Com0_Receive_Data_Buffer[3]&0x07; //¿ªÊ¼µØÖ·³ýÒÔ8µÄÓàÊý
c=Com0_Receive_Data_Buffer[5]+b; //Óаüº¬ÔÚÇ°Ò»¸ö»ý´æÆ÷µÄ²ÎÊý
Com0_Send_Data_Buffer[2]=Com0_Receive_Data_Buffer[5]>>3; //Òª·¢Ë͵Ļý´æÆ÷µÄÊýÁ¿
if(Com0_Receive_Data_Buffer[5]&0x07) //ÓàÊý
Com0_Send_Data_Buffer[2]+=1;
Com0_Send_Data_Bytes=Com0_Send_Data_Buffer[2]+3;
if(c&0x07)
c=(c>>3)+1;
else
c=c>>3;
for(i=0;i<c;i++)
{
temp=Coil_state[a];
a++;
temp+=(Coil_state[a]<<8);
temp>>=b;
Com0_Send_Data_Buffer[i+3]=temp&0xff;
}
Com0_Send_Data_Buffer[i+3]=temp>>8;
Com0_Send_Data_Buffer[i+3]<<=(8-Com0_Receive_Data_Buffer[5]&0x07);
Com0_Send_Data_Buffer[i+3]>>=(8-Com0_Receive_Data_Buffer[5]&0x07);
}
else
{
Com0_Send_Data_Buffer[1]=0x81;
Com0_Send_Data_Buffer[2]=2;
Com0_Send_Data_Bytes=3;
}
}
else
{
Com0_Send_Data_Buffer[1]=0x81;
Com0_Send_Data_Buffer[2]=3;
Com0_Send_Data_Bytes=3;
}
} |
|