Library for Ultrasonic Ranging Module HC-SR04

This library is for the HC-SR04 ultrasonic ranging module . The module is very easy use , now with the library , user just need a function then he can get the distance .

Library includes 3 functions for user :

Ultrasonic(int TP, int EP)

This is a initial function for ultrasonic ranging module, choose the pins for module Trig and Echo pin. You need using this function before Setup() to define the pin map.
example: Ultrasonic(13,12);
then you define the digital pin 13 of Arduino for the Trig pin of HC-SR04. And the pin 12 for Echo pin.

long Timing()

Trigger the ultrasonic ranging module work and return the duration that Echo pin keep high level.
example: long time; Ultrasonic hcsr; time = hcsr.Timing();
Then you start the HC-SR04 for ranging and you get the time the Echo pin keep high, you can change the time corresponds to the distance : Distance = ((Duration of high level)*(Sonic :340m/s))/2

long Ranging(int sys)

If you don't want to change the time into distance yourself , this function will help you get the distance immediate. And the function has a parameter sys, you can use CM or ICN , than you get the distance show as centimeter or inch. This function will call the Timing() and you don't need to use the Timing() before it.
example: long distance; Ultrasonic hcsr; distance = hcsr.Ranging(CM);

:wink: Hope it help.

can not post the post with img before post the normal one ... so ...
reply and show the picture and attach the library

Download the library here

Anyone used this successfully? Either the library or the HC-SR04 in general? With the library and my own version of it I get nothing but seemingly random results around the 1-3cm mark, even when there's nothing in range for far more than that.

Setup is Arduino Duemilanove powering the sensor from 5V/GND pins. Sensor TRIG pin connected to Arduino pin 12, sensor ECHO pin connected to pin 13 (though I've tried other combinations with same results).

#include "Ultrasonic.h"
Ultrasonic ultrasonic( 12, 13 );

void setup()
  Serial.begin( 9600 );

void loop()
  Serial.print( ultrasonic.Ranging(CM) );
  Serial.println( "cm" );


Anyone used this successfully? Either the library or the HC-SR04 in general?

Not sure about the "HC" prefix, but I've had a Devantech SRF04 for years, and it looks identical (even the timing diagram).
I've found it to be reliable.
I'll give the library a shot when I get home.

I had some problems with the first unit I got. ITead replaced the faulty unit and the replacement works great.
I also bought another one that also works fine. I have only tested the units so far, but they seem to be fairly accurate.