串口通讯

#include <reg52.h>

//#define BUFFERLEGTH 10

unsigned
int shuju[4]={0xff,0xfe};
unsigned
char recbuff[2]={0,0};
unsigned
char rec_count=0;
enum{WAIT,START,DATA}; // 状态机
char u_stat=WAIT;

sbit spc
=P0^6; //beep

void UART_init()
{
//初始化串行口和波特率发生器
SCON =0x50; //选择串口工作方式1,打开接收允许
TMOD =0x20; //定时器1工作在方式2,定时器0工作在方式1
TH1 =0xfA; //实现波特率9600(系统时钟11.0592MHZ)
PCON = 0x80;
TR1
=1; //启动定时器T1
ET1 =0;
ES
=1; //允许串行口中断
PS=1; //设计串行口中断优先级
EA =1; //单片机中断允许
}



void COM_send(void)
{
unsigned
char point;
for(point=0;point<4;point++) //连续发送二十位数据
{
SBUF
=shuju[point]; //把缓存区的数据都发送到串口
while(!TI);
TI
=0;
}
}




//--------------------------------------------------------------------------------------------------
void com_interrupt(void) interrupt 4 using 3
{
unsigned
char RECEIVR_buffer;



ES
=0;

if(RI)
{
RI
=0;
RECEIVR_buffer
=SBUF;

switch(u_stat)
{
case WAIT:
if(RECEIVR_buffer==0xff)
{
u_stat
=START;


}
else u_stat=WAIT;
break;

case START:

if(RECEIVR_buffer==0xfe)
{
u_stat
=DATA;

}
else u_stat=WAIT;

break;
case DATA:
if(RECEIVR_buffer==0xee)
{
u_stat
=WAIT;
}
else
{
// COM_send();
recbuff[rec_count]=RECEIVR_buffer;
rec_count
++;
if(rec_count>1) rec_count=0;
}
break;

}
}
ES
=1;

}

posted on 2011-09-13 09:30  码农也疯狂  阅读(322)  评论(0编辑  收藏  举报

导航