We have already sold many HC-SR04 modules , though it’s easy use and we has published a demo ,still some user mail us for a specialized code of his own use — even just change the different Arduino pins for module.
So we decide to release a Arduino Library for those beginning user . You just need to add the library into your Arduino , and call for a function , you can get the distance.
Download the Library , unzip the release package to arduino-0018/libraries/ folder. Open the Arduino IDE , you can include the library by Sketch-Import library-Ultrasonic . And you can find the example sketch in File-Examples-Ultrasonic-UltrasonicDemo .
Here we give out a brief introduction of this ultrasonic ranging library.
It includes 3 function for user :
1. Ultrasonic(int TP, int EP)
This is a initial function for ultrasonic ranging module, choose the pins for module Trig and Echo pin.
then you define the digital pin 13 of Arduino for the Trig pin of HC-SR04. And the pin 12 for Echo pin.
2. 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
3. long Ranging(int sys) — (sys : CM / INC)
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);
OK, now you get the distance in centimeter . It’s very easy , right ?
Download the library for HC-SR04 ultrasonic ranging module here :
Ultrasonic ranging library (unknown, 11,104 hits)