专注电子技术学习与研究
当前位置:单片机教程网 >> MCU设计实例 >> 浏览文章

AVR单片机ATMega16的UART通信总结

作者:萧文   来源:本站原创   点击数:  更新时间:2014年04月01日   【字体:

#include <iom16v.h>
#include <macros.h>

typedef unsigned char uint8_t;


#define DF_Config_Uart0_BaudRate 9600

//UART0 初始化
// desired baud rate: 9600
// actual: baud rate:9600 (0.0%)
void uart0_init(void)
{
 UCSRB = 0x00; //disable while setting baud rate
 UCSRA = 0x00;
 UCSRC = BIT(URSEL) | 0x06;

 // 配置波特率
#if DF_Config_Uart0_BaudRate==9600

//----------11.0592M 9600kbps:
 UBRRL = 0x47; //set baud rate lo
 UBRRH = 0x00; //set baud rate hi
 
#else if  DF_Config_Uart0_BaudRate==19200

 //----------11.0592M 19200kbps:
 UBRRL = 0x23; //set baud rate lo
 UBRRH = 0x00; //set baud rate hi

#endif

 UCSRB = 0x98;
}


// 发送一个字节
void uart0_sendByte(uint8_t dat)
{
  while(!(UCSRA&(1<<UDRE)));  //判断UDR是否为空
  UDR=dat;                      //发送数据
}

// 发送多个字节数据
void uart0_sendData(uint8_t *pDat,uint8_t nCount)
{
uint8_t i;
uint8_t *p = pDat;
for (i=0; i<nCount; i++)
{
uart0_sendByte(*p++);
}
}
// 发送字符串
void uart0_sendString(uint8_t *pDat)
{
uint8_t *p = pDat;
while(*p)
{
uart0_sendByte(*p++);
}
}

// 串口接收中断
#pragma interrupt_handler uart0_rx_isr:iv_USART0_RXC
void uart0_rx_isr(void)
{
 //uart has received a character in UDR
 #if 1 // For test
  uint8_t dat=UDR;
  uart0_sendByte(dat);
 #else
 
 #endif
}

/*-----------------------------------------------------------------
函数名称: void uart_receive(void)
函数功能: 查询方式,接收数据
参    数:
返 回 值: 无
-----------------------------------------------------------------*/
uint8_t uart0_receive(void)    //定义返回值类型,否则出错
{
  while(!(UCSRA&(1<<RXC)));  //判断是否有数据未读出
  return UDR;                //获取并返回接收数据
}

/*

关闭窗口

相关文章