Distance Sensor
Simple Arduino example to print out distance values (in cm) using an HC-SR04 ultrasonic range sensor. .
Components
1 x HC-SR04 ultrasonic range sensor
1 x Arduino Uno
1 x breadboard
jumper wires
Setup
Arduino sketch
Inspect Serial monitor (9600) for distance values in cm.
// set up the range finder, HC-SR04
int rangeTriggerPin = 2;
int rangeEchoPin = 3;
long currentDistance; // (cm)
/**
* initialization code, happens once
**/
void setup()
{
// for printing
Serial.begin( 9600 );
// set up the range finder
pinMode(rangeTriggerPin, OUTPUT);
pinMode(rangeEchoPin, INPUT);
}
/**
* loops after setup
**/
void loop()
{
// get current distance
currentDistance = senseCurrentDistance();
// print it out
Serial.println( currentDistance );
// wait a little before next iteration
delay( 500 );
}
/**
* Use the range finder to determine distance to the
* closest object.
**/
long senseCurrentDistance()
{
// The PING is triggered by a HIGH pulse of 2 or more microseconds.
// Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
digitalWrite(rangeTriggerPin, LOW);
delayMicroseconds(2);
digitalWrite(rangeTriggerPin, HIGH);
delayMicroseconds(5);
digitalWrite(rangeTriggerPin, LOW);
// A different pin is used to read the signal from the PING: 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.
long duration = pulseIn(rangeEchoPin, HIGH);
return microsecondsToCentimeters( duration );
}
/**
* Determine the distance based on how long it took to echo back.
**/
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;
}