#include<reg51.h>
sbitBT_SND=P1^0;
sbitBT_REC=P1^1;
/**********************************************
IO口模拟232通讯程序
使用两种方式的C程序占用定时器0
**********************************************/
#defineMODE_QUICK
#defineF_TMF0
#defineTIMER0_ENABLETL0=TH0;TR0=1;
#defineTIMER0_DISABLETR0=0;
sbitACC0=ACC^0;
sbitACC1=ACC^1;
sbitACC2=ACC^2;
sbitACC3=ACC^3;
sbitACC4=ACC^4;
sbitACC5=ACC^5;
sbitACC6=ACC^6;
sbitACC7=ACC^7;
voidIntTimer0()interrupt1
{
F_TM=1;
}
//发送一个字符
voidPSendChar(unsignedcharinch)
{
#ifdefMODE_QUICK
ACC=inch;
F_TM=0;
BT_SND=0;//startbit
TIMER0_ENABLE;//启动
while(!F_TM);
BT_SND=ACC0;//先送出低位
F_TM=0;
while(!F_TM);
BT_SND=ACC1;
F_TM=0;
while(!F_TM);
BT_SND=ACC2;
F_TM=0;
while(!F_TM);
BT_SND=ACC3;
F_TM=0;
while(!F_TM);
BT_SND=ACC4;
F_TM=0;
while(!F_TM);
BT_SND=ACC5;
F_TM=0;
while(!F_TM);
BT_SND=ACC6;
F_TM=0;
while(!F_TM);
BT_SND=ACC7;
F_TM=0;
while(!F_TM);
BT_SND=1;
F_TM=0;
while(!F_TM);
TIMER0_DISABLE;//停止timer
#else
unsignedcharii;
ii=0;
F_TM=0;
BT_SND=0;//startbit
TIMER0_ENABLE;//启动
while(!F_TM);
while(ii<8)
{
if(inch&1)
{
BT_SND=1;
}
else
{
BT_SND=0;
}
F_TM=0;
while(!F_TM);
ii++;
inch>>=1;
}
BT_SND=1;
F_TM=0;
while(!F_TM);
#endif
TIMER0_DISABLE;//停止timer
}
//接收一个字符
unsignedcharPGetChar()
{
#ifdefMODE_QUICK
TIMER0_ENABLE;
F_TM=0;
while(!F_TM);//等过起始位
ACC0=BT_REC;
TL0=TH0;
F_TM=0;
while(!F_TM);
ACC1=BT_REC;
F_TM=0;
while(!F_TM);
ACC2=BT_REC;
F_TM=0;
while(!F_TM);
ACC3=BT_REC;
F_TM=0;
while(!F_TM);
ACC4=BT_REC;
F_TM=0;
while(!F_TM);
ACC5=BT_REC;
F_TM=0;
while(!F_TM);
ACC6=BT_REC;
F_TM=0;
while(!F_TM);
ACC7=BT_REC;
F_TM=0;
while(!F_TM)
{
if(BT_REC)
{
break;
}
}
TIMER0_DISABLE;//停止timer
returnACC;
#else
unsignedcharrch,ii;
TIMER0_ENABLE;
F_TM=0;
ii=0;
rch=0;
while(!F_TM);//等过起始位
while(ii<8)
{
rch>>=1;
if(BT_REC)
{
rch|=0x80;
}
ii++;
F_TM=0;
while(!F_TM);
}
F_TM=0;
while(!F_TM)
{
if(BT_REC)
{
break;
}
}
TIMER0_DISABLE;//停止timer
returnrch;
#endif
}
//检查是不是有起始位
bitStartBitOn()
{
return(BT_REC==0);
}
voidmain()
{
unsignedchargch;
TMOD=0x22;/*定时器1为工作模式2(8位自动重装),0为模式2(8位
自动重装)*/
PCON=00;
TR0=0;//在发送或接收才开始使用
TF0=0;
TH0=(256-96);//9600bps就是1000000/9600=104.167微秒执行的
timer是
//
104.167*11.0592/12=96
TL0=TH0;
ET0=1;
EA=1;
PSendChar(0x55);
PSendChar(0xaa);
PSendChar(0x00);
PSendChar(0xff);
while(1)
{
if(StartBitOn())
{
gch=PGetChar();
PSendChar(gch);
}
}
}