The HC-SR04 is an ultrasonic distance measurement module. Its appearance looks like a pair of eyes, which is why it’s often mounted on robot cars or robotic insects as their “vision.”
The working principle is simple:
1. First, set the TRIG pin HIGH briefly (a quick HIGH → LOW pulse).
2. The HC-SR04 sends 8 ultrasonic pulses at 40 kHz, and raises the ECHO pin HIGH.
3. When the reflected sound wave returns, the ECHO pin goes LOW again.
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 considerationsThe 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.
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;
![[Tutorial] BW21-CBV-Kit — Ultrasonic Distance Measurement](https://prod.hackster-cdn.online/assets/transparent-a0c1e3063bcabc548a5f3fa7328f3c1c97f747e6e764da4c14439567baa79ae1.gif)







Comments