In this article we consider the principle of operation of the ultrasonic range finder HC-SR04 (Figure 1).
The sensor has 4 pins (standard 2.54 mm):
VCC: “+” power.
TRIG (T): input pin.
ECHO (R): output pin (signal length depends on the distance of the object to the sensor).
GND: “-” power (ground).
The principle of operation of the sensor can be divided into 4 stages
1. Supplies a pulse duration of 10 ms, the withdrawal of Trig.
2. Inside the rangefinder input pulse is converted to 8 pulses of 40 KHz and sent forward through the “T eye”
3. Reaching the obstacles sent pulses are reflected and received “R eye.” Obtain the output on pin Echo.
4. Directly on the controller translates the signal into the distance by the formula:
pulse width (ms) / 58 = distance (cm)
pulse width (ms) / 148 = distance (inch)
Connect the sensor to the Arduino:
VCC to +5 V Arduino.
TRIG to 9 pin Arduino.
ECHO to 8 pin Arduino.
GND to whatever GND pin on Arduino.
In the following sketch we will send distance in port on your computer, as well as at a distance less than 30 cm it will turn on LED connected to 13 pin of Arduino.
#define Trig 9
#define Echo 8
#define ledPin 13 void setup()
pinMode(Trig, OUTPUT); //initiate as output
pinMode(Echo, INPUT); //initiate as input
unsigned int impulseTime=0;
unsigned int distance_sm=0; void loop()
/* Pulse is applied to the input trig rangefinder */
delayMicroseconds(10); // equal to 10 microseconds
digitalWrite(Trig, LOW); // Turning off
impulseTime=pulseIn(Echo, HIGH); // We measure the length of the pulse
distance_sm=impulseTime/58; // Recalculate in centimeters
Serial.println(distance_sm); // Output to port
if (distance_sm<30) // If the distance is less than 30 centimeter
digitalWrite(ledPin, HIGH); // The LED lights
digitalWrite(ledPin, LOW); // otherwise the LED does not light
/* wait for 0.1 seconds, next pulse can be radiated only after the disappearance of the echo from the previous one. This time is called the period of the cycle (cycle period). The recommended period between pulses must be at least 50 ms. */