#include"reg52.h" //头文件包含
#include<intrins.h>
sbit LED0=P1^0; //LED灯个位定义
sbit LED1=P1^1; //LED灯十位定义
sbit LED2=P1^2; //LED灯百位定义
sbit LED3=P1^3; //LED灯千位定义
sbit LED4=P1^4; //LED灯使能
sbit Trig=P1^0; //超声波传感器使能引脚定义
sbit Echo=P3^2; //超声波传感器回波引脚定义
float time=0; //回波总时间
unsigned int distance=0; //距离(cm)
unsigned char timeH=0; //定时器1定时值高八位
unsigned char timeL=0; //定时器1定时值低八位
unsigned char counter=0; //定时器0计数值
unsigned char LedBuf[6];
unsigned char code LED_num[10]={
0xC0,0xF9,0xA4,0xB0,0x99,
0x92,0x82,0xF8,0x80,0x90}; //数码管真值
bit success=0; // 回波接收成功标志
void delay(unsigned int x)// 延时程序(x=1,i=10)时延时50us
{
unsigned int i,j;
for(j=0;j<x;j++)
{
for(i=0;i<10;i++)
{
_nop_();//空指令
_nop_();
}
}
}
void display()
{
signed char i;
unsigned char buf[6];
for(i=0;i<6;i++)
{
buf[i] = (unsigned char)(distance%10);
distance /= 10;
}
for(i=5;i>=1;i--)
{
if(buf[i] == 0)
LedBuf[i] = 0xFF;
else
break;
}
for(;i>=0;i--)
{
LedBuf[i] = LED_num[buf[i]];
}
}
void main(void)
{
Trig = 0; //使能管脚初始拉低
TMOD &= 0x11;//定时器0和1设定为16位工作模式
TH0 = 0x3C; //-5000>>8 = 60
TL0 = 0xB0; //-5000%256 = 176
TR0 = 1; //开定时器0
ET0 = 1; //定时器0中断允许
EX0 = 1; //外部中断0允许
IT0 = 1; //外部中断0下降沿触发
EA = 1; //开总中断
LED3 = 1;
LED4 = 0;
while(1)
{
if(success == 1)//判断是否接收成功
{
distance = (time * 0.017- 10);//根据时间求出距离
success = 0;
}
display();
}
}
void LedScan()
{
static unsigned char i=0;
P0 = 0xFF;
P1 = (P1 & 0xF8) | i;
P0 = LedBuf[i];
if(i<5)
i++;
else
i = 0;
}
void Timer0int() interrupt 1 //50ms*4=0.2s,每0.2秒测一次距
{
EA = 0;
TR0 = 0;
counter++;
if(counter==4)
{
Trig = 1;
delay(1);
Trig = 0;
TH1 = 0;
TL1 = 0;
TR1 = 1;
counter = 0;
}
TH0 = 0x3C;
TL0 = 0xB0;
TR0 = 1;
EA = 1;
LedScan();
}
void exint() interrupt 0 //外部中断0用于检测回波下降沿
{
TR1 = 0;
timeH = TH1;
timeL = TL1;
TH1 = 0;
TL1 = 0;
time = timeH * 256 + timeL;
success = 1;
}
|