# Fun with Arduino 38 Ultrasonic Distance Measurement with HC-SR04

The HC-SR04 is a nice little less than \$1,- device that can be used to measure distance.

It contains a loudspeaker and a microphone. When we send a pulse to its trig input, it will output an ultrasonic (40kHz) sound burst. It then measures the time it takes for the echo to return. We can measure this time via the pulse on the echo output that has exactly that duration.

To make life easy, the Arduino has an instruction to measure the length of a pulse … the pulseIn() command returns the measured time in us:

`measured_time = pulseIn(ECHO_PIN, HIGH); // microseconds`

To calculate the distance of the object that reflected the sound we need to do some math with speed of sound in air, which is 343 m/s, or 0.343 mm/us. To derive the ‘to’ + ‘from’ distance in mm, we multiply the measured_time by 0.343 and then divide by 2 to get the one way distance. We declare distance as a floating point variable (float):

```distance_mm   = (float)measured_time * 0.1715;
distance_inch = distance_mm / 25.4;```

Read on below the video …

Let’s make some code to perform a measurement every second and write the measured distance to the Serial Monitor. We’ll add an output that reacts if the distance is less than a given number of mm to create an object detection, which we can use e.g. to detect a passing train.

```#define TRIG_PIN A0   // output trigger to start measurement
#define ECHO_PIN A1   // input measurement result = duration of HIGH level
#define INTERVAL 1000 // [ms] time between printing the result
#define DISTANCE  100 // [mm] distance for on/off digital out

unsigned long measured_time, time_to_print;
float distance_mm, distance_inch;

if (value < 1000) Serial.print(" ");
if (value <  100) Serial.print(" ");
if (value <   10) Serial.print(" ");
Serial.println(value);
}

void setup() {
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN,  INPUT);
pinMode(13,       OUTPUT);
Serial.begin(9600);
}

void loop() {
digitalWrite(TRIG_PIN,HIGH);
delayMicroseconds(20);
digitalWrite(TRIG_PIN,LOW);

measured_time = (float)pulseIn(ECHO_PIN, HIGH);
distance_mm   = measured_time * 0.1715;
distance_inch = distance_mm / 25.4;

if(distance_mm < DISTANCE) digitalWrite(13,HIGH);
else                       digitalWrite(13, LOW);

if(millis() > time_to_print) {
time_to_print = millis() + (unsigned long)INTERVAL;
Serial.print("  mm: ");
Serial.print("inch: ");