功能:
0.本系统采用STC89C52作为单片机
1.本系统采用LCD1602液晶实时显示测试距离
2.两个功能按键可以设置距离阈值的大小
3.系统报警电路由蜂鸣器和LED组成的声光报警器
3.低于预设距离值将声光报警,距离越近声音越急促
4.采用DC002作为电源接口可直接输入5V给整个系统供电
原理图:
PCB :
主程序:
#include <reg52.h> //包含头文件,一般情况不需要改动,头文件包含特殊功能寄存器的定义#include <stdio.h>#include "lcd1602.h"#include "delay.h"#include "math.h"//管脚定义sbit KEY_ADD = P3^4;sbit KEY_SUB = P3^6;sbit ECHO = P2^5; //超声波引脚定义sbit TRIP = P2^4;sbit BUZZER = P2^2;//变量定义unsigned char dis[16]; //显示数组float f_distance; //距离int f_distanceTH = 1000;//距离阈值mmint BUZZERLater = 0;long g_cnt = 0; //定时器计数bit g_dispFlag = 0;bit BUZZERFlag = 0;bit g_refreshFlag = 0;unsigned char cnt = 0;//函数声明void DispDis();void KeyScan();void Timer1_Init();void main(void){unsigned char testCnt = 0;float f_distanceBuf = 0;TRIP = 0;TMOD |= 0x01; //设T0为方式1,GATE=1;TH0 = 0;TL0 = 0;//ET0=1; //允许T0中断EA = 1; //开启总中断Timer1_Init();LCD_Init(); //初始化液晶DelayMs(20); //延时有助于稳定LCD_Clear();while (1) //主循环{if (g_refreshFlag == 1){g_refreshFlag = 0;if (testCnt >= 10){testCnt = 0;f_distance = f_distanceBuf / 10; //计算10次平均值f_distanceBuf = 0;}else{TR1 = 0;TRIP = 1; //启动一次模块//不可以使用其他终端 容易造成死循环DelayUs10x(1);TRIP = 0;while (!ECHO); //当RX为零时等待TR0 = 1; //开启计数while (ECHO); //当RX为1计数并等待TR0 = 0;TR1 = 1;g_cnt = (long)(TH0 * 256 + TL0);TH0 = 0;TL0 = 0;f_distanceBuf = f_distanceBuf + (float)(g_cnt * 17) / 100.0 * 1.102; //算出来是mm (g_cnt * 340 / 2) / 1000.0 * 1.102;系数testCnt++;}}if ((g_cnt > 0) && (f_distance > 0)){if (f_distance < f_distanceTH) //距离对比{BUZZERFlag = 1;} //报警else{BUZZERFlag = 0;} //不报警}if (g_dispFlag == 1) //刷新液晶{TR1 = 0;DispDis();TR1 = 1;g_dispFlag = 0;}KeyScan();}}void DispDis(){sprintf(dis, "Distance:%5dmm", (int)f_distance);LCD_DispStr(0, 0, dis);sprintf(dis, "THR:%5dmm", f_distanceTH);LCD_DispStr(0, 1, dis);}void KeyScan(){if (!KEY_ADD) //加键按下{DelayMs(100);if (!KEY_ADD){if (f_distanceTH <= 1000){f_distanceTH++;}}}if (!KEY_SUB) //减键按下{DelayMs(100);if (!KEY_SUB){if (f_distanceTH > 0){f_distanceTH--;}} }}//定时器1初始化void Timer1_Init(){TMOD &= 0x0F;TMOD |= 0x10;TH1 = (65536 - 18432) / 256; //20ms定时TL1 = (65536 - 18432) % 256; //20ms定时TR1 = 1;ET1 = 1;EA = 1;}//定时器1中断void Timer1_INT() interrupt 3{TH1 = (65536 - 18432) / 256; //20ms定时TL1 = (65536 - 18432) % 256;if (cnt >= 25){g_dispFlag = 1;cnt = 0;}else{cnt++;}if (cnt % 5 == 0){g_refreshFlag = 1;}if (BUZZERFlag == 1){if (BUZZERLater < (f_distance / 100)){BUZZERLater++;}else{BUZZER = ~BUZZER;BUZZERLater = 0;}}else{BUZZER = 1; //关闭蜂鸣器}}
仿真演示视频:
/video/BV1dG4y187K9/
实物演示视频:
/video/BV1xe411j7nJ/