How distance is calculated
Assuming the speed of sound is 340 m/s, the time needed to travel 1 cm in air is:
340 × 100 × 10⁻⁶ = 29 μs
Because the sound wave travels to the object and back, the total travel distance is double. Therefore, the formula is:
distance = (time / 29) / 2 = time / 58
Important: Voltage considerations
The HC-SR04 operates at 5V. When the ECHO pin outputs a 5V HIGH signal, it can potentially damage the GPIO pins of the BW21-CBV-Kit.
To avoid this, you must step down the voltage using resistors or a level shifter.
Connection diagram (BW21-CBV-Kit + resistors)
Use a 1:2 resistor divider (any suitable values are fine; avoid extremely high resistance). If you don’t have resistors, you can use a logic level converter instead.
Example Code
Open the example from: File → Examples → AmebaGPIO → HCSR04_Ultrasonic
Compile and upload it to the BW21-CBV-Kit, then press the reset button. Open the Serial Monitor —
the measurement result is printed every 2 seconds.
Notes
Since the HC-SR04 uses reflected sound waves, the measured distance may vary depending on the material of the object's surface:
- Rough surfaces may scatter sound
- Soft surfaces may absorb sound
Code Reference
Trigger the measurement by pulsing TRIG HIGH for 10 µs:
digitalWrite(trigger_pin, HIGH);delayMicroseconds(10);digitalWrite(trigger_pin, LOW);
Measure the duration of the HIGH pulse on the ECHO pin:
duration = pulseIn(echo_pin, HIGH);
Calculate the distance:
distance = duration / 58;
Ai-Thinker
haydn jones
Marcin Saj