How to Use an Ultrasonic Sensor with Arduino
It is very easy to use an ultrasonic sensor with Arduino, these can be used to make a robot, musical instruments, etc.. Here is a very simple minimal tutorial for using an ultrasonic sensor with Arduino.
This article needs to be converted to wikiHow format. You can help by editing it now and then removing this notice. Notice added on 2015-01-16. |
EditSteps
-
1Connect the sensor to the Arduino, and write a simple program that displays the distance measured to the Serial Monitor
- There are two commonly available ultrasonic sensors, the HC-SR04 from Sain-Smart, and the Parallax PING. They work in a very similar manner. The HC-SR04 has four wires, and the Parallax has 3 wires. This tutorial covers using the HC-SR04.
- There are four pins on the ultrasonic sensor. Here is how we want to connect them.
- VCC - connect this to one of the 5V power connections on the Arduino UNO.
- GND - connect this to one of the ground connections on the Arduino UNO.
- Trig - connect to port 12.
- Echo - connect to port 13.
-
2Enter in the code. Here is the minimal code you need to get the sensor working. We'll just report the distance measured to the Serial Monitor.
We could really use your help!
room organization?

hairstyling?

estate planning?

singing?

EditSample Code
#define trigPin 12
#define echoPin 13
void setup(){
Serial.begin (9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop(){
int duration, distance;
digitalWrite(trigPin, HIGH);
delayMicroseconds(1000);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1;
if (distance >= 200 || distance <= 0){
Serial.println("Out of range");
}
else{
Serial.print(distance);
Serial.println(" cm");
}
delay(500);
}
These sensors work by emitting a sound pulse, and measuring the time it takes for the pulse to reflect back (we cannot hear the sound, i.e. ultrasonic). Velocity = distance / time, and distance = velocity * time, the sensor will report the time it takes for the pulse to reflect, but we actually want half that amount, because going there and back is actually twice the distance to the object. Then we just need the velocity, which for us is the speed of sound in air.
Upload this code to your Arduino. If you place an object in front of the sensor within its operating range, you should see the distance measured using the Serial Monitor. I was able to get it to work using my hand. Good Luck !
About this wikiHow