HC-SR04

The HC-SR04 Ultrasonic Sensor is a very cheap and neat sensor tha gives eyes to your Arduino. This one comes in a Robot kit from Deal Extreme. It works by sending and receiving (bouncing) ultrasound pulses, thus giving you the distance to the nearest object.

In this sketch we’re going to do, we’ll send a pulse to trigger the detection and then listen for the echo using the pulse() function. The duration of this second pulse is equal to the time taken by the ultrasound to travel to the object and back to the sensor. Using the speed of sound, this time can be converted to distance.

HC1

The connections are pretty simple:

Sensor Arduino
GND GND
Echo PIN 8
Trig PIN 7
Vcc 5V

With the connections made, lets go to programming.

/*
HC - SR04 ping distance sensor
 VCC to 5v
 GND to GND
 Echo to Pin7
 Trig Pin8

*/
#define echoPin 7 //echo
#define trigPin 8 // Trigger
// Variables to hold duration and distance
long duration, distance;
void setup() {

 /* initialize serial port */
 Serial.begin(9600);

 /* Initialize PIN Modes */
 pinMode(trigPin, OUTPUT); // Trigger PIN
 pinMode(echoPin, INPUT); // Echo PIN
}

void loop() {

 /* The following trigPin/echoPin cycle is used to determine the distance of the nearest
 object by bouncing soundwaves off it */

 //Trigger a HIGH pulse for 2 or more microseconds
 //Give a short LOW pulse before sending a HIGH one
 digitalWrite (trigPin, LOW);
 delayMicroseconds(2);

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

 digitalWrite (trigPin, LOW);

 //Now, lets read the read the bounced wave
 duration = pulseIn(echoPin, HIGH);

 //calculate the distance
 distance = microsecondsToCentimeters(duration);
 Serial.print ("cm ");
 Serial.print (distance);

 delay(100);
}

long microsecondsToCentimeters (long microseconds) {
 // The speed of sound is 340 m/s or 29 microseconds per centimeter
 // The ping travels forth and back, so, the distance is half the distance traveled
 return microseconds / 29 / 2;
}

References

http://arduino.cc/en/Tutorial/Ping?from=Tutorial.UltrasoundSensor
http://arduinobasics.blogspot.pt/2012/11/arduinobasics-hc-sr04-ultrasonic-sensor.html