Ultrasonic principle of simple ranging accurate, the application of a wide range of the following a self-written digital tube program, display part of the need to change, the recent contest written I use the Hui Development Board, a common yin digital tube
Ultrasonic Module Program//Author: Z H//time 2015/11/29//trig = p2^0//echo = p3^2 #include <reg52.h> #define UCHAR unsigned cha R #define UINT unsigned int unsigned char code table[]={0x3f,0x06,0x5b,0x4f,0x66, 0x6d,0x7d, 0X07,0X7F,0X6F};
0-9 of the Code table UINT time = 0;
UINT Timeh = 0;
UINT Timel = 0;
UINT Succeed_flag; Sbit dula=p2^0; De Shun signal latch control sbit wela=p2^1;
The latch control sbit Trig = p2^2 of the bit selector signal;
Sbit Echo = p3^2;
void delay (UINT Z) {uint x, y;
for (x=z;x>0;x--) for (y=125;y>0;y--);
}//void Delay_20us () {Uchar A;
for (a=0;a<100;a++); }//***************************************************************//Display data converter void display (UINT temp) {Uchar Qian
, Ge,shi,bai;
Qian = temp/1000;
bai=temp/100%10;
SHI=TEMP%100/10;
ge=temp%10;
Wela=1;
P0=0xf7;
P0 = 0xFE;
wela=0;
Dula=1;
P0=table[qian];
dula=0;
Delay (5);
Wela=1;
P0=0xf7;
P0 = 0XFD;
wela=0;
Dula=1;
P0=table[bai]; dula=0;
Delay (5);
Dula=1; p0=0x00;
Close code dula=0;
Wela=1;
P0=0xef;
P0 = 0XFB;
wela=0;
Dula=1;
P0=table[shi];
dula=0;
Delay (5);
Dula=1; p0=0x00;
Close code dula=0;
Dula=1;
P0=table[ge];
dula=0;
Wela=1;
P0=0XDF;
P0 = 0xf7;
wela=0;
Delay (5);
Dula=1; p0=0x00;
Close code dula=0;
}//*************************************************************** void Main () {UINT distance;
UINT TEST = 0; trig=0; First pull the low pulse input pin ea=1; Open Total interrupt 0 tmod=0x10; Timer 1, 16-bit working mode while (1) {ea=0; Trig=1 of the total interruption of the shutdown; Ultrasonic input terminal delay_20us (); Delay 20US trig=0; Produces a 20us pulse while (echo==0); Wait for Echo echo pin to become high level succeed_flag=0;
Clear measure success sign ea=1; Ex0=1; Open external interrupt 0 th1=0; Timer 1 Clear 0 tl1=0; Timer 1 Clear 0 tf1=0; Count overflow flag tr1=1; Start Timer 1 delay (20); Wait for the result of measurement tr1=0; Off timer 1 ex0=0;
Close External Interrupt 0 if (succeed_flag==1) {Time=timeh*256+timel; distance=time*0.172;
CM display (distance); } if (succeed_flag==0) {distance=0; No echo is clear 0 test =!test; Test Lamp Change}}}//***************************************************************//external interrupt 0, used for judging the echo power flat void Exter () interrupt 0//external interrupt 0 is No. 0 # {Timeh =th1; Remove the value of the timer Timel =TL1; Remove the value of the timer succeed_flag=1;//to the Mark Ex0=0 of the successful measurement; Off external Interrupt}//****************************************************************//Timer 1 interrupt, used as ultrasonic ranging time void timer1 ()
Interrupt 3//{th1=0;
tl1=0; }