AVR单片机串口中断接收程序,实现一个简单的功能,串口中断接收数据,不论数据长短,然后将数据的个数返回给CPU!
程序如下:
#include <avr/io.h>
#include <avr/interrupt.h>
#define fosc 11059200 //时钟频率
#define baud 9600 //串口波特率
#define uint unsigned int
#define uchar unsigned char
uint buf[510];
uchar flag=0;
uint i=0,k=0;j=0;
void mdelay(unsigned int ms) //0.1ms delay
{
unsigned int m=0;
for(;ms>0;ms--)
{
for(m=0;m<56;m++)
{;}
}
}
void uart0_init(void) //串口初始化
{
UCSR0B = 0x00; //disable while setting baud rate
UCSR0A = 0x00;
UCSR0C =(1<<UPM01)|(1<<UCSZ01)|(1<<UCSZ00); //8bit+1bit stop(偶校验)
//UCSR0C =(1<<UCSZ01)|(1<<UCSZ00); //无校验
UBRR0L=(fosc/16/(baud+1))%256;
UBRR0H=(fosc/16/(baud+1))/256; //波特率设置
UCSR0B=(1<<RXEN0)|(1<<TXEN0)|(1<<RXCIE0);
}
void putchar0(unsigned char c)
{
while (!(UCSR0A&(1<<UDRE0)));
UDR0=c;
}
SIGNAL(SIG_OVERFLOW0)
{
TCCR0=00;//关中断
flag=1;
}
SIGNAL(SIG_USART0_RECV)
{
uchar data;
TCCR0=00; //收到数据关闭中断
data=UDR0;
buf=data;
i++;
TCNT0=224;//收完数据开定时中断
TCCR0=0x06;
}
int main(void)
{
DDRE = 0x3C;
PORTE = 0xFF;
DDRA=0xFF;
PORTA=0xEF;
DDRB=0x0f;
PORTB=0xff;
TIMSK=0x01;
uart0_init();
sei();
while(1)
{
if(flag==1)
{
cli();
for(j=0;j<i;j++)
{
putchar0(buf[j]);
}
flag=0;
i=0;
sei();
}
}
}
|