What is the ultrasonic sensor  (distance)? An ultrasound (Sonar) with high-level waves that people cannot hear. However, we can see the presence of ultrasonic waves everywhere in nature. In animals such as bats, dolphins ... use ultrasonic waves to communicate with each other, to hunt or locate in space.

## Ultrasonic sensor (HC - SRF04)

Ultrasonic sensorHC-SR04 (Ultrasonic Sensor) is used very popular to determine the distance because the price is cheap and quite accurate. The HC-SR04 ultrasonic sensor uses ultrasonic waves and can measure distances between 2 -> 300cm.

### Principle of operation

To measure the distance, we will emit a very short pulse (5 microSeconds) from Trig pin. After that, the ultrasonic sensor will generate a HIGH pulse at Echo's feet until it receives a reflected wave on this battery. The width of the pulse will be equal to the time the ultrasonic wave is transmitted from the sensor and back.

The speed of sound in the air is 340 m / s (physical constant), equivalent to 29,412 microSeconds / cm (106 / (340 * 100)). When the time is calculated, we divide by 29,412 to get the distance.

Note:  The further the ultrasonic sensor is, the more incorrect it will be captured, because the scanning angle of the sensor will gradually expand in a cone, in addition to the oblique or rough surface, it will reduce the accuracy of the sensor and parameters. The technique listed below is from the manufacturer of the test under ideal conditions, but in fact depends on the working environment of the sensor.

## Diagram

### Components

Code

Download

```#define TRIG_PIN 3
#define ECHO_PIN 2
#define TIME_OUT 5000

float GetDistance()
{
long duration, distanceCm;

digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);

duration = pulseIn(ECHO_PIN, HIGH, TIME_OUT);

// convert to distance
distanceCm = duration / 29.1 / 2;

return distanceCm;
}

void setup() {
Serial.begin(9600);

pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
}

void loop() {
long distance = GetDistance();

if (distance <= 0)
{
Serial.println("Echo time out !!");
}
else
{
Serial.print("Distance to nearest obstacle (cm): ");
Serial.println(distance);
}
delay(1000);
}```