Introduction: Sonar
Wiring the HC 204 to the Arduino:
VCC to 5V
GND to GND
Trig to pin 3
Echo to pin 2
Supplies
Arduino UNO
HC SR04 ultrasonic sensor
4 jumper wires
breadboard
Step 1: Coding
Step 2: How It Works
The Ultrasonic Sensor
An ultrasonic sensor uses sonar to determine the distance to an object. What the sensor does is as follows:
- the trig pin sends a high frequency sound
- when the signal finds an object, it bounces back
- the echo pin receives it
The time between the transmission and reception of the signal makes it possible to calculate the distance of the object from the sensor. This is possible because sound's velocity in air is known.
The speed of sound is around 340 m/s or .034 cm/microsecond. In order to get the distance in cm, you multiply the received travel time from the echo pin by .034 and divide by 2 because it bounces back and forth. This is from the equation distance = time * speed. the speed would be 0.034 cm/us, the time would be a given pulse (in this case 10 microseconds or 8 cycle sonic bursts), and the distance is the object's distance from the sensor or what we're trying to find.
More on the Code
The trigpin is an output while the echopin is an input. In the loop, the trigpin is cleared by setting the pin on LOW for 2 microseconds. To generate the sound wave, the code sets the trigpin on HIGH for 10 microseconds. Using the pulseIn() function it reads the travel time and puts that value as duration in the code. The function has 2 arguments, the first one is the name of the echo pin and the second one is either HIGH or LOW. HIGH means that the pulseIn() function will wait for the pin to go to HIGH from the bounced sound wave then it starts the timer, then wait for it to go to LOW when the sound wave ends and stop the timing. At the end of the funciton, it returns the length of the pulse in microseconds. For the actual distance, we use the equation distance = time * speed. As explained above, the code multiplies the duration by .034 and divides it by 2 then prints it to the Serial Monitor.
Step 3: Finished Product
Somethings not working?
Distance reads as zero? Make sure you position your sonar with the 2 eyes facing the object.
No serial output? Make sure you’ve installed the correct drivers and are using the appropriate COM port
thanks for reading!