Tuesday, August 20, 2013

Ultrasonic distance measurement using HC-SR04 ultrasonic module + Arduino Pro

Ultrasonic sensors (Ping sensors) are widely used in distance measurement as they are cheap and has a quite good accuracy. I got this cheap HC-SR04 ultrasonic module from ebay and wanted to test it.
I found the datasheet for it from here.

According to the datasheet ;
Max Range = 400cm
Min Range = 2cm

This algorithm should be used to get the echo from the module:
1. Give 10uS pulse to the TRIGGER pin.
2. Measure the pulse width at ECHO pin.
3. Calculate  distance = (echo high level time×velocity of sound) / 2

I connected the module to my Arduino Pro (Techduino) and wrote a small code for the testing. The code will send the calculated distance value to PC via its UART port.

























The code :

#define echo 8
#define trigger 9
long duration,distance;

void setup() {
 Serial.begin (9600);
 pinMode(trigger, OUTPUT);
 pinMode(echo, INPUT);
 digitalWrite(trigger, LOW);
}

void loop() {
 digitalWrite(trigger, LOW);
 digitalWrite(trigger, HIGH);
 delayMicroseconds(10);
 digitalWrite(trigger, LOW);
 duration = pulseIn(echo, HIGH);
 distance = duration/58;
 if ((distance >= 400) || (distance <= 2))
 distance = -1;
 Serial.println(distance);
 delay(60);
 
}
I checked the output from the Arduino to PC using a terminal program.


















After that I coded a small software to get the distance data and show it in a nice way using Visual C#. This is my first C# application and I referred here and here for coding. You can download the source code and application from here.




1 comment:

  1. Hello,

    I can't find any contact info in the site so forgive me for using the comment section. I'm Algen, I work with engineering website EEWeb.com and would love to do an exchange of website links (with your website: http://www.incrediblediy.com) and feature you as a site of the day on EEWeb (you can see an example here http://www.eeweb.com/websites/sparkle-labs/). Is this of interest to you?

    Hope to hear from you soon.

    Sincerely,

    Algen Dela Cruz
    EEweb.com
    [email protected]

    ReplyDelete