Ultrasonic distance measurement using HC-SR04 ultrasonic module + Arduino Pro
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 8I checked the output from the Arduino to PC using a terminal program.
#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);
}
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.
Comments