`
isiqi
  • 浏览: 16067196 次
  • 性别: Icon_minigender_1
  • 来自: 济南
社区版块
存档分类
最新评论

modbus 下位机

J# 
阅读更多

/通信程序中CRC校验函数是核心,其他根据需要修改。程序通过了验证。
#include "iom16v.h"
unsigned int crc=0xffff;
unsigned char data[]={0x05,0x03,0x02,0x04,0x02};
/*串口初始化函数*/
void Uart_Init(void)
{
UCSRA = 0x02; /*倍速*/
UCSRB = 0x18; /*允许接收和发送*/
UCSRC = 0x06; /*8位数据*/
UBRRH = 0x00; UBRRL = 12; /*9600*/
}

void delay(unsigned int ms)//延时
{
unsigned int i,j;
for(i=0;i<ms;i++)
{
for(j=0;j<1142;j++);
}
}
/*数据发送,查询方式*/
void Uart_Transmit(unsigned char i)
{
while (!(UCSRA & (1<<UDRE))); /* 等待发送缓冲器为空*/
UDR = i; /* 发送数据*/
}

/*数据接收,查询方式*/
unsigned char Uart_Receive( void )
{
while (!(UCSRA & (1<<RXC))); /* 等待接收数据*/
return UDR; /* 获取并返回数据*/
}
//================================
//===============CRC校验函数
//=================================
unsigned int cal_crc(unsigned char *ptr, unsigned int len)
{
unsigned int crc=0xffff;
unsigned char i;
while(len!=0)
{
crc^=*ptr;
for(i=0;i<8;i++)
{
if((crc&0x0001)==0)
crc=crc>>1;
else
{
crc=crc>>1;
crc^=0xa001;
}
}
len-=1;
ptr++;
}
return crc;

}

/*主函数*/
void main(void)
{
unsigned int AddNum=0;
DDRA = 0x00; /*方向输入*/
PORTA =0xFF; /*打开上拉*/
DDRB = 0xFF; /*方向输出*/
PORTB = 0xFF; /*电平设置*/
DDRC = 0x00;
PORTC = 0xFF;
DDRD = 0x02;
PORTD = 0xFF;
Uart_Init();

while(1)
{

Uart_Transmit(data[0]);
Uart_Transmit(data[1]);
Uart_Transmit(data[2]);

AddNum++;
data[3]=AddNum/10;
data[4]=(AddNum%10)*10;

if(AddNum==50)
{
AddNum=0;
}

//修改下列值来确定
Uart_Transmit(data[3]);
Uart_Transmit(data[4]);

crc=cal_crc(data,5);
Uart_Transmit(crc); //低字节
Uart_Transmit(crc>>8);//高字节
delay(400);//延时

}
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics