How do you get your project to gauge distance? Here's a tutorial showing you how to use the HC-SR04 Ultrasonic "Ping" sensor.
HardwareThis is a very simple and useful ultrasonic sensor. There are four pins that you would use to interface with the sensor: VCC, Trig (signal output pin), Echo (signal input pin), and GND.
Each of the four pins are connected to the Arduino: VCC to 5v, Trig to a digital pin, Echo to a digital pin, and GND to GND (ground). No resistors are needed, just pin to port!
In this tutorial I have the VCC connected to 5v, GND to GND, Trig to pin 12, and Echo to pin 13.
How does the Ultrasonic Sensor Work?The sensor outputs a muted sound wave out of its speaker (one of the silver barrels) that will bounce off an object and be reflected back to the sensor's microphone (the other silver barrel). After the sound wave is sent out, the sensor will time how long it takes for the reflected sound to get back to the ultrasonic sensor. The operation is kind of like echolocation. There are many quick math equations you can use to convert the pulse time into a unit of measurement (note that these results may not be very accurate).
Programming the Ultrasonic SensorThere is a demo code attached in the Code section. The code will get the pulse inpu and output it onto the serial monitor.
The Ultrasonic sensor can't do the echolocation stuff on its own though, so you will need to program it your self (don't worry, its not very difficult).
First you should make sure you setup the pins correctly in your code (assuming you are using pin 13 as the Echo pin and pin 12 as the Trig pin).
void setup(){
pinMode(13, INPUT); //remember: the Echo pin is the microphone pin
pinMode(12, OUTPUT); //remember: the Trig pin is the speaker pin
}
Then you program the echolocation operation:
digitalWrite(12, LOW); //turn off the Trig pin incase it was on before
delayMicroseconds(2); //a very short break
digitalWrite(12, HIGH); //turn on the Trig pin to send a sound wave
delayMicroseconds(10); //a short break to let the operation happen
digitalWrite(12, LOW); //turn off the Trig pin to end the sound wave output
long dur = pulseIn(13, HIGH); //sensor the sound wave reflection time
There you have it! How to program the Ultrasonic sensor.
Last NotesThe code for performing the echolocation operation and everything else that was said in this tutorial works with most other ultrasonic sensor modules.
Please leave feedback on this tutorial, thank you!
Comments