Day 2.1: Ultrasonic Sensor
Bonus Material for Diligent Students (Released on 3 July 2024)
We appreciate the students who challenged ideas on the afternoon of Day 2. The SWS3009B Teaching teams researched after work and finally got a clear idea about our new Ultrasonic Sensor (HC-SR04A).
Code Explaination
In Day 2's lecture, we used an example code which is provided by the manufacturer of the HC-SR04A; the main methodology (we will call this Method 1) is like this:
Method 1
Here is the code explanation: The third and fourth lines of code generate a 10us high pulse to trigger the trigPin
, causing the ultrasonic transmitter to send out eight 40KHz ultrasonic pulses (source: manufacturer). The first and second lines are just to ensure the pulse is off and have no effect. The fifth line of code turns off the pulse. The pulseIn(echoPin, HIGH)
function in the seventh line of code is used to detect the duration of the high-level signal on the echoPin
, measured in microseconds (us). According to the manufacturer's manual, the duration of the high-level signal on the echoPin
(i.e., the width of the echo pulse) represents the time it takes for the ultrasonic pulse to travel from the transmitter to the receiver. Thus, the formula in the eighth line of code is: distance = (duration * 0.0343) / 2
.
Here, duration is the width of the echo pulse, and 0.0343 cm/us is the speed of sound in the air. We divide by 2 because this time includes the round trip of the ultrasonic pulse from the sensor to the object and back.
Therefore, the width of the echo pulse is directly related to the distance: the farther the distance, the wider the echo pulse; the closer the distance, the narrower the echo pulse.
Method 2
Many students wonder why using a completely different logic to measure distance can also be successful: that is (we will call this Method 2), recording the duration between the trigPin
sending the pulse and the echoPin
receiving the pulse, and then using the same formula, distance = (duration * 0.0343) / 2
, can also yield an accurate distance?
Below is our verification of the HC-SR04A sensor's functionality using an oscilloscope, which we hope will clarify your doubts.
Verification of Signal Waveform from HC-SR04A
When the distance of the ultrasonic wave is reduced to 2 cm (the theoretical minimum detection distance), the resulting waveform looks like this:
We hope this clarifies your doubts. Additionally, regarding the issue we encountered this afternoon where the waveforms of the trigPin
and the echoPin
were exactly opposite, we found after repeated verification that it was caused by a malfunction in the oscilloscope's Channel 2. We have reported this for repair.
Thank you all for raising questions. The teaching team has also learned a lot and reflected on many things during the teaching process. It has been a very rewarding experience for us! :-)
Last updated