Learn the physics behind it, follow the wiring steps one by one, and use efficient C++ code to create a reliable distanceβmeasuring system with an ultrasonic sensor and an Arduino microcontroller.
Quick answer
To set up an ultrasonic sensor with arduino code and circuit, connect the HC-SR04 VCC pin to Arduino 5V, connect GND to ground, attach Trig to digital pin 9, and attach Echo to digital pin 10. The Arduino starts the sensor by sending a 10-microsecond HIGH pulse on pin 9. The sensor then sends a 40 kHz acoustic burst and makes the Echo pin HIGH. By timing this HIGH with pulseIn(), the Arduino works out the distance using the formula: Distance = (Time * 0.0343) / 2.
The Physics of Acoustic Time-of-Flight Sensors
Ultrasonic distance sensors find how far away an object is by timing how long it takes for a highβfrequency sound pulse to travel out and back. This method is called TimeβofβFlight (ToF). The standard HC-SR04 sensor module has two transducers: a transmitter and a receiver. Inside the transmitter is a piezoelectric crystal that shakes when an electric signal is applied, creating a 40 kHz sonic burst. That frequency is far higher than what humans can hear, which tops out at about 20 kHz. The sound wave moves through the air until it hits a surface. Some of the energy bounces back toward the sensor.
The receiver picks up this echo and turns the vibration back into an electrical signal that the microcontroller can read.
For a closely related example, see DHT11 Sensor Interfacing with ESP32: Hardware and Firmware Guide.
Ultrasonic Time-of-Flight Timing Sequence
This sequence shows the exact transition of electrical and acoustic signals during a single measurement cycle.
- 1Trigger Setup
Arduino pulls Trig pin LOW for 2 microseconds to ensure a clean signal start.
- 2Trigger Pulse
Arduino pulls Trig pin HIGH for 10 microseconds to initiate the sensor cycle.
- 3Acoustic Transmission
Sensor internal logic generates eight 40 kHz sonic bursts into the air.
- 4Echo State Change
Echo pin transitions from LOW to HIGH immediately after transmission.
- 5Echo Return
Acoustic wave reflects off target and strikes the receiver transducer.
- 6Pulse Measurement
Echo pin drops to LOW; Arduino records HIGH pulse duration in microseconds.
Wiring the Ultrasonic Sensor with Arduino Code and Circuit
To hook up the HC-SR04 to an Arduino Uno, you need four wires. The sensor runs on a typical 5V DC supply and uses two digital pins for control. Regular breadboard jumper wires work fine for these direct connections. Tie the VCC pin on the sensor to the 5V rail on the Arduino. Tie the GND pin on the sensor to any Arduino ground pin. The sensorβs Trig (Trigger) pin is an input that starts a measurement; connect it to digital pin 9 on the Arduino. The Echo pin is an output that reports how long the sound wave traveled; connect it to digital pin 10 on the Arduino.
If you are using a 3.3V microcontroller, like an ESP32 or a Raspberry Pi Pico, you need a simple resistor voltage divider on the Echo line. This brings the 5V output down to a safe 3.3V level. Feeding a 5V Echo signal straight into a 3.3V GPIO pin can damage or destroy the port.
For a closely related example, see How to Connect ESP32 to WiFi Using Arduino IDE.
Optimised Arduino Code for Distance Measurement
To implement this circuit, upload the following optimized C++ sketch to your Arduino board. This code includes an explicit timeout parameter within the pulseIn function to prevent the program from stalling if no returning echo is detected.
const int trigPin = 9;
const int echoPin = 10;
long duration;
float distanceCm;
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
Serial.begin(9600);
}
void loop() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH, 30000);
if (duration == 0) {
Serial.println("Error: No pulse or out of range");
} else {
distanceCm = (duration * 0.0343) / 2.0;
Serial.print("Distance: ");
Serial.print(distanceCm);
Serial.println(" cm");
}
delay(100);
}
This implementation establishes a stable measurement cycle by writing the trigger pin low before firing the pulse. Setting a 30,000-microsecond timeout limits the search window to approximately 5 meters, preventing the processor from waiting indefinitely when signals are lost.
For a closely related example, see Choosing Between Arduino and Raspberry Pi for Engineering Projects.
Comparison of Common Ultrasonic Sensor Modules
Choose the correct sensor module based on your specific environmental and voltage requirements.
| Factor | Engineering view | Why it matters |
|---|---|---|
| Operating Voltage | HC-SR04: 5V | US-100: 3V to 5V | JSN-SR04T: 3V to 5.5V | US-100 is ideal for direct 3.3V logic connection without level shifting. |
| Measurement Range | HC-SR04: 2cm – 400cm | US-100: 2cm – 450cm | JSN-SR04T: 20cm – 600cm | JSN-SR04T has a larger blind spot of 20cm due to its single-transducer design. |
| Environmental Rating | HC-SR04: Indoor | US-100: Indoor | JSN-SR04T: Waterproof probe | The JSN-SR04T probe is sealed; the control board must remain dry. |
| Acoustic Cone Angle | HC-SR04: 15 degrees | US-100: 15 degrees | JSN-SR04T: 75 degrees | Wider angles increase the chance of receiving unwanted side reflections. |
The Mathematical Formula Behind the Calculation
The distance calculation uses the constant speed of sound in dry air. At a standard ambient temperature of 20 degrees Celsius, sound travels at about 343 meters per second. Because the Arduino measures time in microseconds, we change the speed to centimeters per microsecond.
Dividing 343 meters by 1,000,000 microseconds gives 0.0343 centimeters per microsecond. The pulseIn function returns the total roundβtrip time: the time for the sound wave to go from the sensor to the object, bounce back, and reach the receiver again. To get the oneβway distance, we split that time in half. The resulting formula is:
Distance = (Time * 0.0343) / 2.
Accounting for Ambient Temperature Variations
The speed of sound changes with air temperature. If the temperature swings a lot, using a fixed value of 343β―m/s will cause errors. You can compute a more accurate speed with the equation: Velocity = 331.3 + (0.606β―Γβ―T), where T is the temperature in Β°C.
For instance, when the outdoor temperature is 35 degrees Celsius, the speed of sound becomes about 352.5β―m/s (0.03525β―cm/Β΅s). If you need the measurement to stay stable with temperature changes, add a digital temperature sensor such as the DS18B20. The Arduino can read the temperature on the fly and update the velocity term in the distance calculation, keeping the results accurate.
Acoustic Limitations and Physical Obstacles
Ultrasonic sensors work well for finding flat, solid surfaces, but they have builtβin limits. The sound pulse does not travel in a straight line; it spreads out in a cone, usually limited to 15 degrees. Anything inside that cone can cause an early echo, which makes the reading wrong. What the sensor sees also depends on the material. Soft, porous things like fabric, sponge or wool soak up the sound instead of bouncing it back. This weakens the echo so much that the sensor often thinks there is no target.
Also, if a hard object is angled sharply away from the sensor, the sound bounces off in another direction and does not return to the receiver, so the sensor misses it.
Troubleshooting Serial Monitor and Circuit Failures
If the Arduino Serial Monitor shows nothing or only zeros, work through the possible problems step by step. First, make sure the baud rate you pick in the lowerβright corner of the Serial Monitor is the same as the one in your code: Serial.begin(9600). Next, look at the wiring. A loose ground wire often causes random readings or a total loss of signal. Check that the GND pin on the sensor is connected directly and with low resistance to the Arduino GND pin. If the sensor still reports a constant zero or gives outβofβrange warnings, probe the Echo pin with an oscilloscope or a logic analyzer.
Move an object in front of the sensor and see whether the pulse width changes.
Useful research starting points
Key takeaways
- The HC-SR04 sensor uses acoustic Time-of-Flight to calculate distance by measuring the round-trip travel time of a 40 kHz sound wave.
- A standard 5V ultrasonic sensor requires level shifting on the Echo line when connected to 3.3V microcontrollers to prevent GPIO damage.
- The speed of sound in air is temperature-dependent; dynamic calibration is necessary for high-accuracy applications.
- Using a timeout parameter with the pulseIn function prevents the Arduino code from blocking when no obstacle is detected.
- Soft fabrics and angled surfaces absorb or deflect acoustic signals, leading to false out-of-range readings.
Questions engineers often ask
Why does my ultrasonic sensor return a constant reading of zero?
A constant zero reading typically indicates that the Echo pin is not receiving a signal. Check for loose jumper wires on the Echo and Trig pins. Additionally, ensure the sensor is receiving a stable 5V power supply, as low voltage can prevent the internal acoustic transmitter from firing.
Can I use the HC-SR04 sensor with a 3.3V Arduino board?
Yes, but you must use a voltage divider or logic level shifter on the Echo pin. The sensor outputs a 5V signal on the Echo pin, which can damage 3.3V microcontrollers. Use a 1k-ohm and a 2k-ohm resistor to safely scale the 5V Echo output down to 3.3V.
How do I increase the accuracy of my ultrasonic sensor measurements?
To maximize accuracy, integrate a temperature sensor like the DS18B20 to dynamically update the speed of sound coefficient in your code. Also, ensure the sensor is mounted perpendicular to flat, hard targets and kept away from reflective side walls that fall within its 15-degree sensing cone.
What is the purpose of the 10-microsecond trigger pulse?
The HC-SR04 sensor requires a 10-microsecond HIGH pulse on its Trig pin to initiate a measurement. When this pulse is received, the sensor's internal controller automatically generates and transmits the eight 40 kHz acoustic pulses needed to perform the measurement.
Continue learning: ultrasonic sensor with arduino code and circuit
Explore more embedded systems tutorials and hardware interfacing guides on Fried Engineers.