给你一个可以正常工作的,I/O口自己改。
#include"reg51.h"
#include <intrins.h>
sbit RX=P1^1;//连接Echo
sbit TX=P1^0;//连接Trig
#define GPIO_DIG P0
sbit LSA=P2^2;
sbit LSB=P2^3;
sbit LSC=P2^4;
unsigned int time=0;
unsigned int timer=0;
unsigned long S=0;
bit flag=0;
unsigned char code DIG_CODE[16]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,
0x7f,0x6f,0x77,0x7c,0x39,0x5e,0x79,0x71};
unsigned char disbuff[4]={0,0,0,0};
void DigDisplay()
{
unsigned char i;
unsigned int j;
for(i=0;i<4;i++)
{
switch(i)
{
case(0):
LSC=0;LSB=0;LSA=0; break;
case(1):
LSC=0;LSB=0;LSA=1; break;
case(2):
LSC=0;LSB=1;LSA=0; break;
case(3):
LSC=0;LSB=1;LSA=1; break;
}
GPIO_DIG=disbuff[i];
j=20;
while(j--);
GPIO_DIG=0x00;
}
}
void Conut(void)
{
time=TH0*256+TL0;
TH0=0;
TL0=0;
S=(long)(time*0.17);
if((S>=4000)||flag==1)
{
flag=0;
disbuff[0]=0x5c;//“o”
disbuff[1]=0x72;//“r”
disbuff[2]=0x72;//“r”
disbuff[3]=0x79;//“E”
}
else
{
disbuff[3]=DIG_CODE[S%10000/1000];
disbuff[2]=DIG_CODE[S%1000/100];
disbuff[1]=DIG_CODE[S%100/10];
disbuff[0]=DIG_CODE[S%10/1];
}
}
void zd1() interrupt 1
{
flag=1;
}
void zd3() interrupt 3
{
TH1=0xf8;
TL1=0x30;
DigDisplay();
timer++;
if(timer>=50)
{
timer=0;
TX=1;
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
TX=0;
}
}
void main( void )
{
TMOD=0x11;
TH0=0;
TL0=0;
TH1=0xf8;
TL1=0x30;
ET0=1;
ET1=1;
TR1=1;
EA=1;
while(1)
{
while(!RX);
TR0=1;
while(RX);
TR0=0;
Conut();
}
}
|