|
//===============串口初始化=============
void uart0_init(void)
{
UCSR0B = 0x00; //禁止发送和接收
UCSR0A = 0x00; //倍速异步模式USX0=0
UCSR0C = 0x06; //0000 0110,UCSZ01=1,UCSZ00=1;1位起始位,8位字符,1位停止位
UBRR0L = 25; //设置波特率为19200
UBRR0H = 0; //
UCSR0B = 0x98; //使能发送和接收,使能串口中断
asm("sei");//打开全局中断
}
//*************** UART0 FUNCTION ************************//
void UartSendHY502(unsigned char *cSendBuffer)
{
unsigned char i;
unsigned char cCheckSum = 0;
UCSR0B &= ~(1<<RXCIE0); //禁止串口接收
for(i=0;i<30;i++)
g_cReceBuf[30] = 0;
while(!(UCSR0A & (1<<UDRE0)));
UDR0 = 0xAA; //发送包头 0xAA
while(!(UCSR0A & (1<<UDRE0)));
UDR0 = 0xBB; //发送包头 0xBB
for (i=0; i<cSendBuffer[0]; i++)
{
cCheckSum ^= cSendBuffer[i];
while(!(UCSR0A & (1<<UDRE0)));
UDR0 = cSendBuffer[i]; //发送长度字、命令字、校验和
if (cSendBuffer[i] == 0xAA)
{
while(!(UCSR0A & (1<<UDRE0)));
UDR0 = 0x00; //在0xAA后加0x00
}
}
while(!(UCSR0A & (1<<UDRE0)));
UDR0 = cCheckSum; //发送校验字
UCSR0B |= 1<<RXCIE0; //打开串口接收
}
SIGNAL(SIG_USART0_RECV)
{
unsigned char i;
unsigned char cReceivedData;
unsigned char cCheckSum = 0;
cReceivedData = UDR0;
if(g_bReceAA)
{
g_bReceAA = 0;
if(cReceivedData == 0xBB )
g_cReceNum = 0;
}//不接收包头AA BB
else
{
if (0xAA == cReceivedData)
g_bReceAA = 1;
g_cReceBuf[g_cReceNum++] = cReceivedData;
if (g_cReceNum > g_cReceBuf[0])//代表所有数据已经接收完毕
{
UCSR0B &= ~(1<<RXCIE0); //禁止串口接收,退出中断服务
cCheckSum = 0;
for (i=0; i <= g_cReceBuf[0]; i++)
cCheckSum ^= g_cReceBuf[i];
if (0 == cCheckSum)
{
g_bReceCommandOk = 1;//表示数据接收完毕 ,且接收无误
}
g_cReceNum = 0;
g_bReceAA = 0;
}
}
}
/************************** main function start here *******************************/
int main(void)
{
uchar CardSN[] = {0x02,0x02};
uchar cStatus;
uchar *cPa;
uart0_init();
cPa = CardSN;
UartSendHY502(cPa); //发送指令
_delay_ms(200); // delay for module execution
cStatus = !g_bReceCommandOk;
//一下为显示部分
if((g_cReceBuf[1] != cPa[1])|| (cStatus != 0x00)) //判断是否接收完毕,及接收的是否正确
{
……
}
else
{
……
}
} |
阿莫论坛20周年了!感谢大家的支持与爱护!!
知道什么是神吗?其实神本来也是人,只不过神做了人做不到的事情 所以才成了神。 (头文字D, 杜汶泽)
|