標(biāo)題:
單片機串口1中斷收發(fā)
[打印本頁]
作者:
京兆府111
時間:
2018-6-17 13:45
標(biāo)題:
單片機串口1中斷收發(fā)
/************* 功能說明 **************
串口1全雙工中斷方式收發(fā)通訊程序。本例程使用22.1184MHZ時鐘,如要改變,請修改下面的"定義主時鐘"的值并重新編譯。
串口設(shè)置為:115200,8,n,1.
通過PC向MCU發(fā)送數(shù)據(jù), MCU收到后通過串口把收到的數(shù)據(jù)原樣返回.
******************************************/
/************* 本地常量聲明 **************/
#define MAIN_Fosc 22118400L //定義主時鐘
#define RX1_Lenth 32 //串口接收緩沖長度
#define BaudRate1 115200UL //選擇波特率
#define Timer1_Reload (65536UL -(MAIN_Fosc / 4 / BaudRate1)) //Timer 1 重裝值, 對應(yīng)300KHZ
#define Timer2_Reload (65536UL -(MAIN_Fosc / 4 / BaudRate1)) //Timer 2 重裝值, 對應(yīng)300KHZ
#include "STC15Fxxxx.H"
/************* 本地變量聲明 **************/
u8 idata RX1_Buffer[RX1_Lenth]; //接收緩沖
u8 TX1_Cnt; //發(fā)送計數(shù)
u8 RX1_Cnt; //接收計數(shù)
bit B_TX1_Busy; //發(fā)送忙標(biāo)志
/************* 本地函數(shù)聲明 **************/
/**********************************************/
void main(void)
{
B_TX1_Busy = 0;
RX1_Cnt = 0;
TX1_Cnt = 0;
S1_8bit(); //8位數(shù)據(jù)
S1_USE_P30P31(); //UART1 使用P30 P31口 默認(rèn)
// S1_USE_P36P37(); //UART1 使用P36 P37口
// S1_USE_P16P17(); //UART1 使用P16 P17口
/*
TR1 = 0; //波特率使用Timer1產(chǎn)生
AUXR &= ~0x01; //S1 BRT Use Timer1;
AUXR |= (1<<6); //Timer1 set as 1T mode
TH1 = (u8)(Timer1_Reload >> 8);
TL1 = (u8)Timer1_Reload;
TR1 = 1;
*/
AUXR &= ~(1<<4); //Timer stop 波特率使用Timer2產(chǎn)生
AUXR |= 0x01; //S1 BRT Use Timer2;
AUXR |= (1<<2); //Timer2 set as 1T mode
TH2 = (u8)(Timer2_Reload >> 8);
TL2 = (u8)Timer2_Reload;
AUXR |= (1<<4); //Timer run enable
REN = 1; //允許接收
ES = 1; //允許中斷
EA = 1; //允許全局中斷
while (1)
{
if(TX1_Cnt != RX1_Cnt) //收到過數(shù)據(jù)
{
if(!B_TX1_Busy) //發(fā)送空閑
{
B_TX1_Busy = 1; //標(biāo)志發(fā)送忙
SBUF = RX1_Buffer[TX1_Cnt]; //發(fā)一個字節(jié)
if(++TX1_Cnt >= RX1_Lenth) TX1_Cnt = 0; //避免溢出處理
}
}
}
}
/********************* UART1中斷函數(shù)************************/
void UART1_int (void) interrupt UART1_VECTOR
{
if(RI)
{
RI = 0;
RX1_Buffer[RX1_Cnt] = SBUF; //保存一個字節(jié)
if(++RX1_Cnt >= RX1_Lenth) RX1_Cnt = 0; //避免溢出處理
}
if(TI)
{
TI = 0;
B_TX1_Busy = 0; //清除發(fā)送忙標(biāo)志
}
}
復(fù)制代碼
作者:
51.MCU
時間:
2021-6-27 18:28
如何實驗?
歡迎光臨 (http://www.torrancerestoration.com/bbs/)
Powered by Discuz! X3.1