How to use Ultrasounds Module with Arduino

Posted on by
Ultrasounds Module for Arduino.

Ultrasounds Module for Arduino.

Measure distances using ultrasonic sensors with Arduino is very common, but not only distances are measured, are also used in robotics for obstacle detection. If you are thinking of using one of these modules in your projects then we explain how the HC-SR04 sensor works.

How works

Ultrasonic modules are used to calculate distances based on the time it takes to detect its own echo. Knowing that sound travels at a speed of 340 m/s and the time it takes the sound generated by the sensor from being emitted until the echo is received, we can calculate the distance between the sensor and the object that reflects sound. In the sensor HC-SR04 activate the ultrasound emission putting the Trig pin to 1 for 10 microseconds, then the pin Echo will be 1 since the sound is emitted until it stops detecting their echo. So that by measuring this time and multiplying by the speed of sound we know the distance has come.

Specifications

Power supply 5V
Angle 60°
Range 2cm – 450cm
Accuracy ±0,3cm
Pinout VCC: VCC
GND: GND
Trig: Digital input
Echo: Digital output

Connect to Arduino

Conexión de Módulo de Ultrasonidos con Arduino UNO.

Conexión de Módulo de Ultrasonidos con Arduino UNO.

We connect the two power pins with Arduino and also need a digital output pin for Trigger and a digital input pin for the Echo. In this example we used the pin 12 for the Trigger and pin 11 for the Echo.

Code

There are several things must be taken into account in the code, first to facilitate calculations we have converted the sound speed of meters per second (340) to centimeters per microsecond (0.034) because the timing of the Echo is  in microseconds directly multiplying the speed will be the distance in centimeters. Secondly we must have the mind that time we measure is the one that takes the ultrasound to go to the object and back to the sensor again, so that the distance to be measured is actually half of which we have calculated .

const int soundSpeed = 0.034; //Centimeters per microsecond
const int trigPin = 12;
const int echoPin = 11;

// variables
long duration;
int distance;

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

void loop() {
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);

duration = pulseIn(echoPin, HIGH);

distance= duration*speedSound/2;

Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
}
Comments are disabled