单片机串口通信C程序及应用实例

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

一、程序代码

#include//该头文件可到网站下载#define uint unsigned int

#define uchar unsigned char

uchar indata[4];

uchar outdata[4];

uchar flag;

static uchar temp1,temp2,temp3,temp;

static uchar R_counter,T_counter;

void system_initial(void);

void initial_comm(void);

void delay(uchar x);

void uart_send(void);

void read_Instatus(void);

serial_contral(void);

void main()

{

system_initial();

initial_comm();

while(1)

{

if(flag==1)

{

ES = 0;

serial_contral();

ES = 1;

flag = 0;

}

else

read_Instatus();

}

}

void uart_send(void)

{

for(T_counter=0;T_counter<4;T_counter++)

{

SBUF = outdata[T_counter];

while(TI == 0);

TI = 0;

}

T_counter = 0;

}

uart_receive(void) interrupt 4

{

if(RI)

{

RI = 0;

indata[R_counter] = SBUF;

R_counter++;

if(R_counter>=4)

{

R_counter = 0;

flag = 1;

}

}

}

void system_initial(void)

{

P1M1 = 0x00;

P1M0 = 0xff;

P1 = 0xff; //初始化为全部关闭

temp3 = 0x3f;//初始化temp3的值与六路输出的初始值保持一致

temp = 0xf0;

R_counter = 0;

T_counter = 0;

}

void initial_comm(void)

{

SCON = 0x50; //设定串行口工作方式:mode 1 ; 8-bit UART,enable ucvr TMOD = 0x21; //TIMER 1;mode 2 ;8-Bit Reload

PCON = 0x80; //波特率不加倍SMOD = 1

TH1 = 0xfa; //baud: 9600;fosc = 11.0596

IE = 0x90; // enable serial interrupt

TR1 = 1; // timer 1

RI = 0;

TI = 0;

ES = 1;

EA = 1;

}

void delay(uchar x)

{

uchar i,j;

for(i=0;i

for(j=0;j<110;j++);

}

serial_contral(void)

{

if(indata[3] == ((indata[0]^indata[1])^indata[2]))

{

if(indata[1]== 0x01)

{

P0 = 0xff;

temp2 = P0; //读取四路输入

// temp2 = temp2&0x0f;

outdata[0] = 0xee;

outdata[1] = 0x02;

outdata[2] = temp2;

outdata[3] = ((outdata[0]^outdata[1])^outdata[2]);

uart_send();

return;

}

if(indata[1]== 0x03)

{

temp3 = indata[2];

P1 = temp3; //控制六路输出

return;

}

if(indata[1]==0x04)

{

outdata[0] = 0xee;

outdata[1] = 0x05;

outdata[2] = temp3;

outdata[3] = ((outdata[0]^outdata[1])^outdata[2]);

uart_send();

return;

}

}

}

void read_Instatus(void)

{

P0 = 0xff;

temp1 = P0; //读取四路输入

if(temp1!=temp)

{

delay(10);

P0 = 0xff;

temp1 = P0;

if(temp1!=temp)

{

temp = temp1;

//P0 = 0xff;

//temp = P0;

//temp = temp&0x0f;

outdata[0] = 0xee;

outdata[1] = 0x06;

outdata[2] = temp;

outdata[3] = ((outdata[0]^outdata[1])^outdata[2]);

uart_send();

}

}

}

//总结:原因在于串口中断接收一定要使用全局变量,并且这个变量R_counter和T_counter 要在主程序中初始化。这样,当串口有数据进来时,系统进入中断接收程序,就不会出现数组混乱送出的问题。

二、原理图

相关文档
最新文档