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

MEGA16单片机_UART程序

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

 

 
 最常用的配置方式
 
UCSRB=0x00;
UCSRA=0x00;     //控制寄存器清零
UCSRC=(1<<URSEL)|(0<<UPM0)|(3<<UCSZ0);//选择UCSRC,异步模式,禁止校验,1位停止位,8位数据位
baud=MCLK/16/baud-1    //波特率最大为65K
UBRRL=baud;         
UBRRH=baud>>8;    //设置波特率
UCSRB=(1<<TXEN)|(1<<RXEN)|(1<<RXCIE);//接收、发送使能,接收中断使能
SREG=BIT(7);                 //全局中断开放
DDRD|=0X02;                 //配置TX为输出(很重要)
 
 就是编程三个寄存器与设置波特率。调通简单,调精不容易。
#include "uart.h"
void main(void)
{
   uchar *str = "Hello World!";
    SystemInit();
    UartInit(19200);
  while(1)
  {
   if(flag)
   {
    flag = 0;
    //Show(rdata,1);
    UartSendB(rdata);
    PutString(str);
    CR();
    SPACE();
   }
  } 
}
//////////////////////////////////////////////////////////////////////
#include <iom16v.h>
#include <macros.h>
#include "uart.h"
 
#define  mclk   8000000
#pragma interrupt_handler UartRx:12
volatile uchar rdata;
uchar flag=0;
/*void delay(uint ms)
{
 uchar i;
 while(--ms)
 {
     for(i=1141;i>0;--i);
 }
}*/
//**********************************************************************
//函 数 名:     void PutString(unsigned char  *puts)
//功    能:   发送字符串到串口
//说    明:     
//参    数:     发送的字符串
//返 回 值:
//示    范:   putstring("\r\n")
//***********************************************************************
    void PutString(uchar  *puts)
   {
       //for(;*puts!=0;puts++)   //遇到停止符0结束
    while(*puts!=0)
    {
       UartSendB(*puts++);
    }
   }
void UartInit(uint baud)
{
  UCSRA &= 0x00;
  UCSRB &= 0x00;
  UCSRC |= 0x86;//寄存器选择、字符长度为8,
  baud = mclk/16/baud-1;
  UBRRL = baud;
  UBRRH = baud>>8;
  UCSRB = 0x98;//接收中断使能、接收使能、发送使能
  SREG |= 0x80;
  DDRD |= 0x02;//TX为输出(重要)
}
void UartSendB(uchar data)
{
 while(!(UCSRA & 0x20));//UDRE为空时置位
 UDR  = data;
 while(!(UCSRA & 0x40));//TXC为空时置位
 UCSRA |= 0x40;
}
void UartRx(void)
{
 UCSRB &= 0x7F;//接收结束中断禁止
 rdata = UDR;  //存储缓冲区的数据
 flag = 1;  //接收标志置位
 UCSRB |= 0X80;//接收结束中断使能
}
void SystemInit(void)
{
  DDRA |= (1<<2)|(1<<3)|(1<<4)|(1<<6);
 DDRB |= 0xFF; 
 PORTA |= (1<<2)|(1<<6);
 PORTB = 0xFF; 
 PORTA &= (~(1<<2))&(~(1<<6));
}
//////////////////////////////////////////////////////////////////////////
#ifndef __UART_H__
#define __UART_H__
#include <iom16v.h>
#include <macros.h>
#define CR() PutString("\r\n")        //CR=回车换行
#define SPACE() UartSendB(0x20)         //发送一个空格。
#define  uchar unsigned char
#define  uint  unsigned int
extern volatile uchar rdata;
extern uchar flag;
//void delay(uint ms);
void UartInit(uint baud);
void UartSendB(uchar data);
void UartRx(void);
void SystemInit(void);
void PutString(uchar  *puts);
#endif
 
关闭窗口