新聞中心

EEPW首頁 > 嵌入式系統(tǒng) > 設計應用 > IAR For AVR 串口中斷接收

IAR For AVR 串口中斷接收

作者: 時間:2016-12-03 來源:網(wǎng)絡 收藏
應用芯片: AT Mega16 晶振: 7.3728MHz

代碼文件: uart_int.c

本文引用地址:http://butianyuan.cn/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;

//###########################################################
/*串口初始化函數(shù)*/
voidUart_Init(void)
{
UCSRB = (1< UCSRC = (1<

UBRRH=0x00; //設置波特率寄存器低位字節(jié)
UBRRL=47; //9600 //設置波特率寄存器高位字節(jié)

SREG_I= 1; //開總中斷
DDRD_Bit1=1; //配置TX為輸出(很重要)
}
//###########################################################
/*發(fā)送一個字符數(shù)據(jù),查詢方式*/
voidUart_Transmit(uchar data)
{
while(!(UCSRA&(1< //也可以寫成 while(UCSRA_UDRE==0);
UDR = data; // 發(fā)送數(shù)據(jù)
}
//###########################################################
/*中斷接收*/
#pragma vector=USART_RXC_vect
__interrupt void USART_RXC_Server(void)
{
UCSRB_RXCIE = 0; //關串口中斷
c = UDR ; //將收到的值賦值給變量
Uart_Transmit(c); //發(fā)給串口以檢測對錯
UCSRB_RXCIE = 1; //開串口中斷
}
//###########################################################
/*主函數(shù)*/
void main(void)
{
Uart_Init();
delay_us(20); //串口初始化后,必須延時20us以上才能發(fā)送數(shù)據(jù),否則會出現(xiàn)錯誤
Uart_Transmit(0x64);

while(1)
{ ; } //此時可以用串口助手發(fā)送字符,然后可以正確接收
}



關鍵詞: IARAVR串口中斷接

評論


技術專區(qū)

關閉