IAR For AVR 串口中斷接收
代碼文件: uart_int.c
本文引用地址:http://www.ex-cimer.com/article/201612/325111.htm|_________DELAY.H
##############################################
DELAY.H :
#ifndef __IAR_DELAY_H
#define __IAR_DELAY_H
#include
#define XTAL7.3728//可定義為你所用的晶振頻率(單位Mhz)
#define delay_us(x) __delay_cycles ( (unsigned long)(x * XTAL) )
#define delay_ms(x) __delay_cycles ( (unsigned long)(x * XTAL*1000) )
#define delay_s(x) __delay_cycles ( (unsigned long)(x * XTAL*1000000) )
#endif
uart_int.c :
#include
#include "delay.h"
#define uchar unsigned char
#define uint unsigned int
uchar c;
//########################################################### UBRRH=0x00; //設(shè)置波特率寄存器低位字節(jié)
/*串口初始化函數(shù)*/
voidUart_Init(void)
{
UCSRB = (1<
UBRRL=47; //9600 //設(shè)置波特率寄存器高位字節(jié)
SREG_I= 1; //開(kāi)總中斷
DDRD_Bit1=1; //配置TX為輸出(很重要)
}
//###########################################################
/*發(fā)送一個(gè)字符數(shù)據(jù),查詢(xún)方式*/
voidUart_Transmit(uchar data)
{
while(!(UCSRA&(1<
UDR = data; // 發(fā)送數(shù)據(jù)
}
//###########################################################
/*中斷接收*/
#pragma vector=USART_RXC_vect
__interrupt void USART_RXC_Server(void)
{
UCSRB_RXCIE = 0; //關(guān)串口中斷
c = UDR ; //將收到的值賦值給變量
Uart_Transmit(c); //發(fā)給串口以檢測(cè)對(duì)錯(cuò)
UCSRB_RXCIE = 1; //開(kāi)串口中斷
}
//###########################################################
/*主函數(shù)*/
void main(void)
{
Uart_Init();
delay_us(20); //串口初始化后,必須延時(shí)20us以上才能發(fā)送數(shù)據(jù),否則會(huì)出現(xiàn)錯(cuò)誤
Uart_Transmit(0x64);
while(1)
{ ; } //此時(shí)可以用串口助手發(fā)送字符,然后可以正確接收
}
評(píng)論