#include<reg52.h>
#include "intrins.h"
#define uchar unsigned char
#define uint unsigned int
uint bai,shi,ge,shifen,time,distance,i,a;
sbit trig=P3^2; //超声波发送
sbit echo=P3^3; //回波接收
sbit smg0=P2^0;
sbit smg1=P2^1;
sbit smg2=P2^2;
sbit smg3=P2^3;
uchar code table0[]={0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90};
uchar code table1[]={0x40,0x79,0x24,0x30,0x19,0x12,0x02,0x78,0x00,0x10};
void initial(void)
{
TMOD=0x01;
TH0=0;
TL0=0;
TR0=0;
EA=0;
}
void delay(uchar i)
{
uchar j;
for(j=i;j>0;j--)
{}
}
uint ultrasonic(void)
{
trig=0;
echo=1;
delay(500);
trig=1;
delay(100);
trig=0;
while(!echo)
TR0=1;
while(echo)
TR0=0;
time=TH0*256+TL0;
return (time*1.7)/100;
TH0=TL0=0;
}
void display(uint distance)
{
bai=distance/1000;//分离百位
shi=distance%1000/100;//分离十位
ge=distance%100/10;//分离个位
shifen=distance%10;//分离十分位
P0=table0[bai];
smg0=0;
delay(500);
P0=0xff;
smg0=1;
P0=table0[shi];
smg1=0;
delay(500);
P0=0xff;
smg1=1;
P0=table1[ge];
smg2=0;
delay(500);
P0=0xff;
smg2=1;
P0=table0[shifen];
smg3=0;
delay(500);
P0=0xff;
smg3=1;
}
void main(void)
{
initial();
distance=ultrasonic();
for(i=0;i<=1000;i++)
{
display(distance);
}
}
|