Devantech SRF04 and 05 Ultrasonic Sensor

The Devantech SRF04 and SRF05 ultrasonic sensors are easy to use and reasonably accurate distance ranging sensors. To use them, you send the sensor s pulse of 10 microseconds on its INIT pin. Then the sensor sends out an ultrasonic pulse and waits for the pulse to bounce off something and return an echo. The sensor then pulses its ECHO pin. The length of the pulse in microseconds is proportional to the distance of the object from the sensor. The code below reads a Devantech sensor on an Arduino or Wiring module.

/*
  Ultrasonic Sensor sketch

  This program reads a Devantech SRF04 ultrasonic distance sensor
  The SRF04 sensor's pins are connected as described below.
  Created 9 November 2006
  By Tom Igoe and Neilson Abeel
*/

#define echoPin 2             // the SRF04's echo pin
#define initPin 3             // the SRF04's init pin
unsigned long pulseTime = 0;  // variable for reading the pulse

void setup() {
  // make the init pin an output:
  pinMode(initPin, OUTPUT);
  // make the echo pin an input:
  pinMode(echoPin, INPUT);
  // initialize the serial port:
  Serial.begin(9600);
}

void loop() {
  // send the sensor a 10microsecond pulse:
  digitalWrite(initPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(initPin, LOW);

  // wait for the pulse to return. The pulse
  // goes from low to HIGH to low, so we specify
  // that we want a HIGH-going pulse below:

  pulseTime = pulseIn(echoPin, HIGH);

  // print out that number
  Serial.println(pulseTime, DEC);
}