This simple program demonstrates how simple it is to use the HC-SR04 to measure distance with centimeter resolution.
The principle of operation is that of the sonar. Applying a pulse of 10 microseconds to TRIG, HC-SR04 emits an ultrasonic signal. When the reflected wave is received, ECHO signal is raised (0-1-0) for a time proportional to the time taken, outward and return. In our program all is managed by HCSR04 VAR.
The INIT is called with the pin number for pulse and echo (pin 4 and 5 that you can change). It sets the TRIG Method for the Echo pin and wait, till the and of the program, for computing the distance.
The TRIG does a very simple job: it computes the microsecond between the set (1) and reset (0) of the ECHO edge signal.
#if(trg_edge);
eTime=trg_tmrUs;
#else;
#while(1);
#if(~eTime);
mTime=trg_tmrUs-etime;
eTime=£;
#break;
#end;
yield;
#end;
#end;
Sampling and FilteringThe main loop of the INIT method sends a pulse and waits for a reply (mTime
not NULL) or a timeOut
. The code has a two stage filtering:
- After three valid values the middle is used
- The average is computed on the last 5 values
The result value (distance) is shown in the following page.
The APP is contained in PowerBerry SUP (StartUpPackage
) and is in executable source code that you can open/study/change with POWER-Ki WorkBench.
POWER-Ki and PowerBerry can be used freely.
Comments
Please log in or sign up to comment.