| 
 
| #include <iom16v.h> #include <macros.h>
 #define  uchar unsigned char
 #define  uint  unsigned int
 
 #define  mclk   8000000
 
 void usart_init(void)//Fosc=8M, 格式N81
 {
 /* 设置波特率*/
 
 UCSRB=0;//禁止发送和接收
 UBRRH=0;
 UBRRL=51;
 /* 接收器与发送器使能*/
 UCSRB = (1<<RXEN)|(1<<TXEN)|(1<<RXCIE);
 /* 设置帧格式: 8 个数据位, 1 个停止位*/
 UCSRC = (1<<URSEL)|0x06;
 
 DDRD|=0x02; //0000 0010 后两位1位txd PD1  0为RXD PD0
 
 
 }
 
 /*延时函数*/
 void delay(uint ms)  //延时秒
 {
 uint i,j;
 for(i=0;i<ms;i++)
 {
 for(j=0;j<1141;j++);
 }
 }
 
 void port_init()      //初始化端口
 {
 
 DDRC = 0xff;
 DDRD = 0xff;//设置PA、PC、PD端口均为输出
 
 PORTC = 0x00;
 PORTD = 0x02;
 }
 
 void uart_sendB(uchar data)
 {
 while(!(UCSRA&(BIT(UDRE)))) ;
 UDR=data;
 }
 
 void main()
 {   uchar i;
 port_init();
 usart_init();
 while(1)
 {
 for(i=0;i<10;i++)
 {
 PORTC|=BIT(6) ; //RS485始终为发送状态
 delay(50);
 uart_sendB(i);
 delay(500);
 PORTC&=(~BIT(6));
 }
 }
 }
 | 
 |