Introduction: How to Make a Simple Arduino Ultrasonic Distance Sensor

About: I am a 14 year old kid that is interested in mechanics and electronics. I build and fix things from earphones to cars.

This will be a simple tutorial on how to make a Arduino Ultrasonic Distance sensor in Centimeters. You will need to know basic electronics, Arduino, and how to use a breadboard.

Step 1: What Is a Ultrasonic Sensor

A ultrasonic sensor is a sensor that sends out high frequency sound waves that bounces off an object and gets reflected back to the sensor to the Arduino. The diagram shows how it works. This is the same way bats can tell how far they are from objects and prey. That is really how it works, pretty simple.

Step 2: What You Need?

You will need

ultrasonic sensor

arduino

wires

usb cable

computer

Step 3: Schemactic

The schematic is pretty straightforward. The VCC and GND wires go to the VCC and GND terminals of the sensor. The trig terminal goes to pin 2. The echo terminal goes to pin 3.

Step 4: The Code

const int trigPin = 2;

const int echoPin = 3;

void setup() { // initialize serial communication: Serial.begin(9600); }

void loop() { // establish variables for duration of the ping, // and the distance result in inches and centimeters: long duration, inches, cm;

// The sensor is triggered by a HIGH pulse of 10 or more microseconds. // Give a short LOW pulse beforehand to ensure a clean HIGH pulse: pinMode(trigPin, OUTPUT); digitalWrite(trigPin, LOW); delayMicroseconds(2); digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW);

// Read the signal from the sensor: a HIGH pulse whose // duration is the time (in microseconds) from the sending // of the ping to the reception of its echo off of an object. pinMode(echoPin, INPUT); duration = pulseIn(echoPin, HIGH);

// convert the time into a distance inches = microsecondsToInches(duration); cm = microsecondsToCentimeters(duration); Serial.print(inches); Serial.print("in, "); Serial.print(cm); Serial.print("cm"); Serial.println(); delay(100); }

long microsecondsToInches(long microseconds) { // According to Parallax's datasheet for the PING))), there are // 73.746 microseconds per inch (i.e. sound travels at 1130 feet per // second). This gives the distance travelled by the ping, outbound // and return, so we divide by 2 to get the distance of the obstacle. // See: http://www.parallax.com/dl/docs/prod/acc/28015-PI... return microseconds / 74 / 2; }

long microsecondsToCentimeters(long microseconds) { // The speed of sound is 340 m/s or 29 microseconds per centimeter. // The ping travels out and back, so to find the distance of the // object we take half of the distance travelled. return microseconds / 29 / 2; }

Then go to the serial monitor to see the distance

Step 5: Closing

That was the tutorial on how to use the sensor. If you need help post in the comments.BYE!