ATMega8 中斷方式UART測(cè)試程序
#include
#include
#include
#define uchar unsigned char
#define uint unsigned int
uchar g_bTxdPos=0; //發(fā)送定位計(jì)數(shù)器
uchar g_bTxdLen=0; //等待發(fā)送字節(jié)數(shù)
uchar g_bRxdPos=0; //接收定位計(jì)數(shù)器
uchar g_bRxdLen=0; //等待接收字節(jié)數(shù)
uchar g_aSendBuf[16]; //發(fā)送數(shù)據(jù)綬沖區(qū)
uchar g_aRecvBuf[16]; //接收數(shù)據(jù)緩沖區(qū)
//接收中斷
SIGNAL(SIG_UART_RECV)
{
uchar c=UDR;
if(g_bRxdLen>0)
{
g_aRecvBuf[g_bRxdPos++]=c;
g_bRxdLen--;
}
}
//發(fā)送中斷
SIGNAL (SIG_UART_TRANS)
{
if(--g_bTxdLen>0)
UDR=g_aSendBuf[++g_bTxdPos];
}
//是否接收完成
uchar IsRecvComplete(void)
{
return g_bRxdLen==0;
}
//從發(fā)送緩沖區(qū)發(fā)送指定長(zhǎng)度數(shù)據(jù)
void SendToUart(uchar size)
{
g_bTxdPos=0;
g_bTxdLen=size;
UDR=g_aSendBuf[0];
while(g_bTxdLen>0);
}
//接收指定長(zhǎng)度數(shù)據(jù)到接收緩沖區(qū)
void RecvFromUart(uchar size,uchar bwait)
{
g_bRxdPos=0;
g_bRxdLen=size;
if(bwait)
while(g_bRxdLen>0);
}
int main( void )
{
uchar i;
//uart初始化
//接收使能、發(fā)送使能、接收中斷允許、發(fā)送中斷允許
UCSRB=(1<
sei();//總中斷允許
while(1)
{
//異步接收16字節(jié)數(shù)據(jù)
RecvFromUart(16,0);
//等待接收完成
while(!IsRecvComplete());
//將接收到的數(shù)據(jù)復(fù)制到發(fā)送緩沖區(qū)
for(i=0;i<16;i++)
g_aSendBuf=g_aRecvBuf;
//發(fā)送回接收到的數(shù)據(jù)
SendToUart(16);
}
}