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.
POWER-KI WorkBench : 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.
Sampling and Filtering
The 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.
Get Used to and Learn
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.