Arduino – Ultrasonic Distance Sensor

Description:

This recipe shows you how to use an Ultrasonic Distance Sensor to determine the distance of objects away from your Arduino Project.

You will be able to view the distance measurements in both centimeters and inches by using the Serial Monitor.

Parts:

  • Arduino Uno
  • Ultrasonic Distance Sensor
  • Breadboard
  • Wires

Code:

  • Once code is uploaded to Arduino go to Tools -> Serial Monitor in the Arduino IDE.
  • Make sure speed is set to 9600 in lower right hand corner
#define trigPin 8
#define echoPin 9

long duration;
float distanceCM;
float distanceInch;

void setup() {
pinMode(trigPin, OUTPUT); 
pinMode(echoPin, INPUT); 
Serial.begin(9600); 
}

void loop() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);

digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);

duration = pulseIn(echoPin, HIGH);

distanceCM = duration * 0.034 /2;
distanceInch = duration * 0.0133 /2;

Serial.print("Distance: ");
Serial.print(distanceCM);
Serial.print("  CM  -  ");

Serial.print(distanceInch);
Serial.println("  Inches");

delay(1000);
}

Code with Comments:

//set digital pins for ultrasonic distance sensor
#define trigPin 8
#define echoPin 9

//create variables needed to calculate distance
//long is a variable type that can be a number up to 2,147,483,647
long duration;
//float is a variable type that is a number with a decimal 
float distanceCM;
float distanceInch;

void setup() {
//set pinMode for ultrasonic distance sensor pins
pinMode(trigPin, OUTPUT); 
pinMode(echoPin, INPUT); 
//begin serial output at 9600
Serial.begin(9600); 
}

void loop() {
//send ultrasonic signal from sensor
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);

//read how long it takes for signal to return to sensor and set the value to duration
duration = pulseIn(echoPin, HIGH);
//change duration variable into useful measurements
distanceCM = duration * 0.034 /2;
distanceInch = duration * 0.0133 /2;

//print values and text to serial monitor
Serial.print("Distance: ");
Serial.print(distanceCM);
Serial.print("  CM  -  ");
Serial.print(distanceInch);
Serial.println("  Inches");

//delay for 1 second.  No technical reason for this, it just makes it easier to read.
delay(1000);
}

Extra Credit:

Try getting close to the sensor with different materials and at different angles to see how well the sensor does or does not perform in detecting the objects.