Materials
- BW21-CBV-Kit × 1
- HC-SR04 Ultrasonic Sensor × 1
- Step-down resistor or voltage regulator
Example
Its working principle is as follows: first, the TRIG pin is set “high” (pulled high and then low). The HC-SR04 then emits eight 40 kHz ultrasonic pulses and sets the ECHO pin high. When the sound waves return, the ECHO pin is pulled low.
Assuming the speed of sound is 340 m/s, the time it takes for sound to travel 1 cm in air is:
1340 s/cm≈29 μs/cm\frac{1}{340} \text{ s/cm} \approx 29 \, \mu\text{s/cm} 3401 s/cm≈29μs/cm
Since the ultrasonic wave travels twice the distance between the HC-SR04 and the object, the distance can be calculated as:
distance=time29×2=time58\text{distance} = \frac{\text{time}}{29 \times 2} = \frac{\text{time}}{58} distance=29×2time=58time
The HC-SR04 operates at 5V. Pulling the ECHO pin high to 5V may damage the BW21-CBV-Kit’s GPIO pins. To prevent this, follow the steps below to reduce the voltage:
BW21-CBV-Kit Wiring Diagram:
We use a resistor with a 1:2 ratio. Any resistor value can work, but overly high resistance is not recommended. If no resistor is available, a level shifter can be used instead.
BW21-CBV-Kit Wiring Diagram + Resistor:
Next, open the example code via File → Examples → AmebaGPIO → HCSR04_Ultrasonic.
Compile and upload the code to the BW21-CBV-Kit, then press the reset button. Open the serial monitor to see the calculated results output every 2 seconds.
- Note: The HCSR04 module calculates distance based on ultrasonic reflection. Therefore, results may be affected by the surface material of objects (e.g., rough surfaces may scatter sound waves, while soft surfaces may absorb them).
Code Reference
Before starting measurement, pull the TRIG pin high for 10 μs, then low. This signals the HC-SR04 that a measurement is about to begin:
digitalWrite(trigger_pin, HIGH);
>span class="16">
digitalWrite(trigger_pin, LOW);
Next, use pulseIn to measure the time the ECHO pin stays high:
duration = pulseIn (echo_pin, HIGH);
Finally, calculate the distance using the formula:
distance = duration / 58;
Ai-Thinker
haydn jones
Marcin Saj
Johnny