#include <reg51.h>
#include <intrins.h>
#include <math.h>
#define uchar unsigned char
#define uint unsigned int
sbit BEEP = P2^5;
sbit Trig = P1^0;
sbit Echo = P1^1;
sbit P24 = P2^4;
sbit P23 = P2^3;
sbit P22 = P2^2;
char tab1[] = {0xc0, 0xf9, 0xa4, 0xb0, 0x99, 0x92, 0x82, 0xf8, 0x80, 0x90};
int a, b, c,o=30;
void delay(unsigned int xms) {
unsigned int i, j;
for (i = xms; i > 0; i--)
for (j = 112; j > 0; j--);
}
void init() {
TMOD = 0x21; // T0工作在定时器方式一模式
TH0 = 0x00; // 赋初值
TL0 = 0x00; // 赋初值
TH1 = 0xfd; // 赋初值
TL1 = 0xfd; // 赋初值
PCON=0x00;
SCON=0xd0;
TR0 = 0; // 初始化不启动
TR1 = 1;
}
float GetDistance(unsigned int time) {
double distance;
distance = (int)time * 0.017; // cm 距离=高电平时间×声速/2 0.017cm/us
return distance; // 将距离返回主函数
}
unsigned int RunOnce() {
unsigned int time;
Trig = 0;
Trig = 1;
init();
Trig = 0;
while (!Echo); // 未收到返程波形,继续计时
TR0 = 1;
while (Echo); // 收到返程波形echo=0,停止计时
TR0 = 0;
time = (TH0 * 256 + TL0) * 1.2;
TH0 = 0; // 清零
TL0 = 0;
return time;
}
void main() {
unsigned int time = 0;
double distance;
P0 = 0xff;
while (1) {
time = RunOnce(); // 传感器接收到高电平的时间
distance = GetDistance(time);
if(distance<=0x10)
{
SBUF=distance;
while(TI==0);TI=0;
delay(500);
}
else
{
while(o--)
{
BEEP = !BEEP;//产生一定频率的脉冲信号
delay(1);//延时1ms
}
}
}
}