#include<reg52.h> #include<string.h>
#define TBUF_SIZE 4 #define RBUF_SIZE 4
unsigned char tbuf[TBUF_SIZE];//发送缓冲区 unsigned char rbuf[RBUF_SIZE];//接收缓冲区
unsigned char r_head; unsigned char t_head; //发送缓冲区的头计数器 unsigned char t_len; //要发送数据的长度 unsigned char temp = 0; //临时计数器 unsigned char remp = 0; //临时计数器
unsigned char count; unsigned char code Ret[4] = "00ok"; unsigned char code Err[4] = "0err"; unsigned char rxdata[6];
bit rflag;
/*******串行口初化函数**************/ void com_initialize(void) { EA = 0; t_head = 0; //清除接收和发送缓冲区 t_len = 0;
PCON = 0x00; //SMOD = 0 SCON = 0xD0; //串行口方式3,11位异步收发。允许接收,清除发送中断标志,清除接收中断村志 T2CON = 0x34; //0011,0100定时器2的溢出脉冲作串口发送时钟,和接收时钟.启动定时器2
#if 1 RCAP2H = 0x0ff; //22.1184MHz 单倍速9600 RCAP2L = 0x0b8; #else RCAP2H = 0x0ff; //22.1184MHz 双倍速9600 RCAP2L = 0x071; #endif
ES=1; //允许串行中断/ TR2 = 1; //启动T2 EA = 1; }
/*启动发送*/ void com_send_data(unsigned char *senddata, unsigned char len) { unsigned char i; t_len = len; //发送的长度 for(i = 0; i < t_len; i++) { tbuf = senddata; } rflag = 0; memset(rbuf,0,4); TI = 1; //开始发送 }
unsigned char checksum(unsigned char *puInBuf, unsigned char puInBufLen) { unsigned char i; unsigned char ucRet = 0; for (i = 0; i <= puInBufLen-1; i++) { ucRet ^= puInBuf; } return(ucRet); } /*******************中断处理函数********************/ //串行口中断(完成数据的接收和发送) void com_isr(void) interrupt 4 using 2 { if(RI) { RI = 0; rbuf[r_head++]=SBUF; if(r_head == 4) { rflag =1; r_head = 0; } /*ch=SBUF; if(ch > 127) { rbuf[count++] = ch; checksum = ch - 128; } else { rbuf[count++] = ch; checksum ^= ch; if((count == RBUF_SIZE)&&(!checksum)) { rflag = 1; count = 0; } } */ } else if(TI) { TI = 0; if(t_head >= t_len) { t_head = 0; } else { SBUF = tbuf[t_head++]; } } }
void main(void) { unsigned int i=10000; unsigned char j; com_initialize(); while(1) { if(rflag)//如果取数标志已置位,就将读到的数从串口发出 { j = !checksum(&rbuf, 4); switch(j) { case 0: //P1 = rbuf[1]; com_send_data(&Err, 4); while(--i); break; case 1: P1 = rbuf[1]; com_send_data(&Ret, 4); while(--i); break; default:break; } } } }
我的这个串口程序经常出现校验不正确!并且还经常丢数据。搞了一周还是没有结论!请各位高手指点小弟一下!!! |