How to Make a Simple Arduino Ultrasonic Distance Sensor

by coolyyz154 in Circuits > Arduino

4169 Views, 25 Favorites, 0 Comments

How to Make a Simple Arduino Ultrasonic Distance Sensor

003.JPG

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.

What Is a Ultrasonic Sensor

478127552_092.jpg
SensorPingOperation.png

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.

What You Need?

004.JPG

You will need

ultrasonic sensor

arduino

wires

usb cable

computer

Schemactic

arduino ultrasonic module hc-sr04 distance sensor code.jpg

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.

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

Closing

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