Ultrasonic Sensor (HC-SR04) Arduino Basic Example

The following tutorial will show you the bare minimum code required to use an ultrasonic sensor (HC-SR04) with arduino. In this tutorial the measured value will be shown in the serial monitor in “cm”.

Ultrasonic distance measurements comes for the nature. It is based on the time travelled by a source of sound reflected from objects to measure the distance between the source of sound and the object. Ultrasonic sound sensors has a transmitter and a receiver part. the actual sound distance is from the transmitter to the receiver so we need to divide the result by two to get the actual distance.

Ultrasonic distance measurements

To calculate the distance we need the speed of sound (approximatelty 340 meters per second). The formula we use will be the following:

Distance = (Time * SpeedOfSound)/2

The Time (duration) based on the measurement will be in microseconds and we want the result in centimeter so the formula will be the following:

Distance = (Duration * 0.034)/2

To use the HC-SR04 ultrasonics sensor a 10us Trigger impulse is requred at the sensor trigger pin and wait for the pulse incoming at the echo pin.

HC-SR04 ultrasonic sensor

Wirring diagram for the sensor is the following. VCC to the 5V, GND to the GND, Trigger pin is connected to the D3 and Echo pin to the D2.

Arduino HC-SR04 wirring diagram

For the distance measurement we use the pulseIn function to measure the time at the echo pin. For mroe detailed guide follow the pulseIn guide at the Arduino.cc website:


The code is the following:

int trigPin = 3;
int echoPin = 2;

unsigned long duration;
int distance;

// The setup() function runs once each time the micro-controller starts
void setup()
	pinMode(trigPin, OUTPUT);
	pinMode(echoPin, INPUT);


// Add the main program code into the continuous loop() function
void loop()
	digitalWrite(trigPin, LOW); //Set the Trigger PIN to LOW state

	digitalWrite(trigPin, HIGH); //Pull up the Trigger pin for 10 microsec
	digitalWrite(trigPin, LOW);

	duration = pulseIn(echoPin, HIGH); //wait for the reflection duration in the echo pin

	String resultString = "Distance is "; //Result String

	distance = (duration * 0.034 )/ 2; //Distance calculation

	resultString +=distance; //Add result to the string
	resultString += "cm";

	Serial.println(resultString); // Print out the string to the serial port



The result will be shown in the Serial Monitor window

Ultrasonic Sensor Measurement Arduino Code for HC-SR04

Leave a Reply

Your email address will not be published. Required fields are marked *