Measure Distance HCSR04 Ultrasonic
Materials
AMB82-mini x 1
HC-SR04 Ultrasonic x 1
Dropping resistor or Level converter
Example
AMB82 MINI Wiring Diagram:
AMB82 MINI Wiring Diagram:
Next, open the sample code in “File” -> “Examples” -> “AmebaGPIO” -> “HCSR04_Ultrasonic”
Compile and upload to Ameba, then press the reset button. Open the Serial Monitor, the calculated result is output to serial monitor every 2 seconds.
Note that the HCSR04 module uses the reflection of sound wave to calculate the distance, thus the result can be affected by the surface material of the object (e.g., harsh surface tends to cause scattering of sound wave, and soft surface may cause the sound wave to be absorbed).
Code Reference
Before the measurement starts, we need to pull high the TRIG pin for 10us and then pull low. By doing this, we are telling the HC-SR04 that we are about to start the measurement:
digitalWrite(trigger_pin, HIGH);
delayMicroseconds(10);
digitalWrite(trigger_pin, LOW);
Next, use pulseIn to measure the time when the ECHO pin is pulled high.
duration = pulseIn (echo_pin, HIGH);
Finally, use the formula to calculate the distance.
distance = duration / 58;