串行双向通信实验c语言程序,115.2K串行通信C语言示例

//115.2k串行口通信程序,校验方式为简单双向校验,

//而且是必要的,因为任何采用中断、crc等的方法

//均很难保证速度和避免错误.

//总体速度5KB/秒

//单片机程序

//使用22.1184晶振

unsigned char TIme,b_break,b_break_3;

//35.555ms

void int_t0(void) interrupt 1 {

TH0=0;

if ((++b_break_3)>2) b_break=1;

TIme++;

}

//

unsigned char rec(void) {

TH0=0;b_break_3=0;b_break=0;

while (RI==0) {

if (b_break) return(1);  //等待pc发送100ms超时

}

RI=0;

SBUF=SBUF;

return(SBUF);

}

/*返回1表示失败*/

bit sen(unsigned char d) {

SBUF=d;

TH0=0;b_break_3=0;b_break=0;

while (RI==0) {

if (b_break) return(1);  //等待pc送回相同字节数据,100ms超时

}

RI=0;

if (SBUF!=d) return(1);

return(0);

}

void main(void) {

unsigned int i;

unsigned char d;

EA=1;

SCON=0xd8;PCON=0x80;

TMOD=0x21;

TL1=TH1=0xff;TR1=1;

TH0=0;ET0=TR0=1;

while (1) {

d=rec();

if ((!b_break)&&(d==0x55)) {

d=rec();

if (!b_break) {

if (d==0xaa) {

//接收到pc送来的要求发送指令0xaa55

for (i=0;i<1000;i++) {

if (sen(i)) {

//发送错误

break;

}

}

} else if (dd==0xaa) {

//接收到pc送来的要求接收指令0xaaaa

for (i=0;i<1000;i++) {

d=rec();

if (!b_break) {

//正确接收处理

} else {

//接收错误处理

break;

}

}

}

}

}

}

}

//电脑程序tc2.0

#i nclude "stdio.h"

#i nclude "dos.h"

#i nclude "process.h"

#i nclude "string.h"

#i nclude "conio.h"

#i nclude

unsigned char TIme_out;

void init_com1(void) {

outportb(0x3fb,0x80);

outportb(0x3f8,1);

outportb(0x3f9,0x0);

outportb(0x3fb,0x3);

}

void sen_com1(unsigned char d) {

long i;

TIme_out=0;

while (!(inportb(0x3fd)&0x20));

outportb(0x3fd,0x0);

outportb(0x3f8,d);

i=clock();

while (1) {

if (clock()>(i+8)) {time_out=1;return;}

if ((inp(0x3fd)&0x1)==1) break;

}

if (inp(0x3f8)!=d) {time_out=2;return;}

}

unsigned char rec_com1(void) {

long i;

unsigned char d;

time_out=0;

i=clock();

while (1) {

if (clock()>(i+8)) {time_out=1;return(0);}

if ((inp(0x3fd)&1)==1) break;

}

d=inp(0x3f8);

while (!(inportb(0x3fd)&0x20));

outportb(0x3fd,0x0);

outportb(0x3f8,d);

return(d);

}

void main(void) {

int i;

long st;

init_com1();

st=clock();

sen_com1(0xaa);

if (time_out) {printf("CPU not ready!");exit(-1);}

sen_com1(0xaa);

if (time_out) {printf("CPU not ready!");exit(-1);}

for (i=0;i<1000;i++) {

sen_com1(i);

if (time_out) {printf("CPU not ready!");exit(-1);}

}

printf("Total use %3.2f S.",(clock()-st)/18.2);

exit(1);

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值