此程序现已应用在自己的一个项目中十分安稳,编写过程中参阅了51hei网站里边的http://www.51hei.com/mcu/1541.html 这篇文章.部分子程序节选于此.
#include “reg52.h”
#include “intrins.h”
#include “math.h”
#include “stdio.h”
sbit BT_SND =P1^5;
sbit BT_REC =P1^6;
sbit LED =P1^7;
bit LED_flage=1;
//单片机IO 口模仿232串口通讯程序
//运用两种方法的C程序 占用定时器0
#define MODE_QUICK
#define F_TM F0
#define TIMER0_ENABLE TL0=TH0; TR0=1;
#define TIMER0_DISABLE TR0=0;
sbit ACC0= ACC^0;
sbit ACC1= ACC^1;
sbit ACC2= ACC^2;
sbit ACC3= ACC^3;
sbit ACC4= ACC^4;
sbit ACC5= ACC^5;
sbit ACC6= ACC^6;
sbit ACC7= ACC^7;
void IntTimer0() interrupt 1
{
F_TM=1;
}
//发送一个字符
void PSendChar(unsigned char inch)
{
#ifdef MODE_QUICK
ACC=inch;
F_TM=0;
BT_SND=0; //start bit
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
unsigned char ii;
ii=0;
F_TM=0;
BT_SND=0; //start bit
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
}
//接纳一个字符
unsigned char PGetChar()
{
#ifdef MODE_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
return ACC;
#else
unsigned char rch,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
return rch;
#endif
}
//查看是不是有开始位
bit StartBitOn()
{
return (BT_REC==0);
}
//定时器1初始化
void Time1_Init(void)
{
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;
}
//发送字符串
void Send_Char(char *byte)
{
int i=0;
for(i=0;*(byte+i)!=;i++)
{
PSendChar(*(byte+i));
}
}
//void delay(int x)
//{
//int a,b;
//for(a=x;a>0;a–)
//for(b=10;b>0;b–);
//}
//void main()
//{
// unsigned char gch;
// Time1_Init();
// LED=0;
// // Send_Char(“S00.0C00.0%E00.0C00.0%L00000lx”);
// while(1)
// {
//
// PSendChar(1);
// delay(1000);
//// if(StartBitOn())
//// {
//// gch=PGetChar();
//// if(gch==1)
////{
//// LED=LED_flage;
//// delay(1000);
//// LED_flage=~LED_flage;
////}
////
//// }
//
// }
//
//}