HC-SR04 Ultrasonic Sensor Library for Arduino

Some days ago my new HC-SR04 ultrasonic sensor for my new Arduino board arrived. In order to keep the overview of my programs, I have written a small library for the sensor which I want to share with you here. As the library is pretty much self-explicatory in my opinion, I will not further comment the following code at this point.

UltraSonic.h

/*
  UltraSonic.h - A library for the HC-SR04 UltraSonic sensor.
  Created by B. Blechschmidt, May 25, 2013.
  Released into the public domain.
*/

#ifndef UltraSonic_h
	#define UltraSonic_h

	#include "Arduino.h"

	class UltraSonic
	{
	  public:
		byte TriggerPin, DataPin;
		UltraSonic(byte TriggerPort, byte DataPort, unsigned int MaximumRange = 400);
		unsigned int ReadCentimeters();
		void ReadCentimetersAsync(int &Centimeters);
	  private:
		unsigned long AsyncTime;
		byte AsyncState;
		unsigned long AsyncLength;
		unsigned int Timeout;
	};

#endif

UltraSonic.cpp

/*
  UltraSonic.cpp - A library for the HC-SR04 UltraSonic sensor.
  Created by B. Blechschmidt, May 25, 2013.
  Released into the public domain.
*/

#include "Arduino.h"
#include "UltraSonic.h"

UltraSonic::UltraSonic(byte TriggerPort, byte DataPort, unsigned int MaximumRange)
{
  Timeout = MaximumRange * 58;
  TriggerPin = TriggerPort;
  DataPin = DataPort;
  pinMode(TriggerPin, OUTPUT);
  digitalWrite(TriggerPin, LOW);
  pinMode(DataPin, INPUT);
  AsyncState = 0;
}

unsigned int UltraSonic::ReadCentimeters()
{
      digitalWrite(TriggerPin, HIGH);
      delayMicroseconds(10);
      digitalWrite(TriggerPin, LOW);
      return pulseIn(DataPin, HIGH, Timeout)/58;
}

void UltraSonic::ReadCentimetersAsync(int &Centimeters)
{
  switch(AsyncState)
  {
    case 0:
    {
      Centimeters = -1;
      digitalWrite(TriggerPin, HIGH);
      AsyncTime = micros();
      AsyncState++;
      break;
    }
    case 1:
    {
      if(micros() >= AsyncTime + 10)
      {
        AsyncState++;
        digitalWrite(TriggerPin, LOW);
        AsyncTime = micros();
      }
      break;
    }
    case 2:
    {
      if(digitalRead(DataPin) == HIGH)
      {
        AsyncState++;
        AsyncTime = micros();

      }
      else if(micros() - AsyncTime > Timeout)
      {
        Centimeters = 0;
        AsyncState = 4; 
      }
      break;
    }
    case 3:
    {
      if(digitalRead(DataPin) == LOW)
      {
        Centimeters = (micros() - AsyncTime) / 58;
        AsyncState++;
      }
      else if(micros() - AsyncTime > Timeout)
      {
        Centimeters = 0;
        AsyncState++;
      }
      break;
    }
    case 4:
    {
      Centimeters = -1;
      AsyncState = 0;
      break;
    }
  }
}

Copy the above files to your Arduino libraries located at C:\Program Files\Arduino\libraries. Please be aware that you might need to create a new folder.