
Interfacing of Multiple Ultrasonic Sensor With Arduino

Hello friends! Today we will connect three HC-SR04 ultrasonic sensors to an Arduino Uno. A single forward-facing sensor is useful for a basic distance demonstration, but a robot may also need information from its left and right sides. The original project used this arrangement to discuss obstacle detection and movement between two walls.
If you have not yet obtained stable readings from one module, begin with Interfacing an Ultrasonic Sensor with Arduino. Here we will build on that measurement function while addressing the main new issue: several sensors can hear one another. Adding more input pins does not automatically create independent acoustic measurements.
We will preserve the original right, left and front pin assignments, trigger the sensors sequentially and report whether each result is valid. We will also calculate the time needed for a complete set of readings. Those timing details matter when a robot moves between measurements.
Plan the Three-Sensor Arrangement
Each HC-SR04 has a trigger input and an echo output in addition to power and ground. Arduino requests a measurement through Trig and measures Echo pulse duration. With three modules, we need three trigger signals and three separate echo inputs for this straightforward arrangement.
Keep a fixed relationship between each physical sensor, its pin pair and its printed name. A correct distance labeled Front when it came from the left side is still wrong information for a navigation algorithm. Label jumper wires and sensor positions before writing application decisions.
| Position | Trig | Echo | Power |
|---|---|---|---|
| Right | Arduino D3 | Arduino D2 | Suitable 5 V supply and common ground |
| Left | Arduino D4 | Arduino D5 | Suitable 5 V supply and common ground |
| Front | Arduino D7 | Arduino D8 | Suitable 5 V supply and common ground |
The reference sheet for the conventional HC-SR04 describes the trigger-and-echo interface and recommends a measurement cycle longer than 60 ms. We will leave a quiet interval after each acquisition instead of immediately firing the next module.
Why Multiple Sensors Can Interfere
An ultrasonic receiver detects returning sound; it does not receive a unique digital identifier attached to every transmitted burst. If two modules transmit close together, sound from one can reach the other directly or after reflecting from a surface. The second module may then associate an unintended return with its measurement.
This interference is often called crosstalk. It can produce believable but incorrect values, so rejecting only zero readings is insufficient. A plausible 40 cm result is not automatically a reflection from the intended target.
Sequential triggering helps, but is not a guarantee
Start one measurement, finish or time it out, and then allow a quiet interval before starting another. This reduces overlap between acoustic activity. The necessary spacing depends on the physical arrangement, reflecting environment and sensor behavior; a single delay value cannot certify every installation.
For a nominal 4 m target distance and 343 m/s sound speed, the direct outward-and-return path takes 8/343 seconds, or about 23.3 ms. Longer reflected paths can arrive later. That calculation explains the scale of the timing problem without assuming that all echoes disappear as soon as the first measurement completes.
Mounting also matters. Sensors aimed directly at each other can have a strong unwanted acoustic path. A chassis edge, floor or wall can redirect sound between them. Compare each sensor operating alone with the same sensor operating in the full sequence to identify interference introduced by the arrangement.
Wire the Modules
Disconnect power and connect each module according to the pin table. Join grounds so the UART-free digital signals have a common electrical reference. Connect the sensor supply to an appropriate regulated source and check the total current demand rather than assuming that more modules can always be added without consequence.
The retained diagram shows the original three-module arrangement. Keep the three Echo outputs separate. They are driven signals, so joining them together can create electrical contention and destroys the information about which module produced the pulse.
For a simple power-budget example, if one particular module draws 15 mA under a documented operating condition, three would contribute approximately 45 mA under the same assumption. Add the controller and other loads, and allow for actual module variation. The example is arithmetic, not a substitute for the supply and module ratings.
Check the controller voltage
This wiring targets a classic 5 V Uno. For a 3.3 V controller, verify the Echo input voltage and provide suitable level conversion where needed. Having three sensors means three echo interfaces to check; solving the voltage issue on one channel does not protect the other two.
Motor power can also disturb sensor readings through supply dips or ground noise. Begin with the sensors on a stationary bench before adding motors. If readings degrade only when motors start, investigate supply distribution and wiring as well as acoustic movement.
Arduino Code for Sequential Measurements
The sketch uses an array to keep each sensor's name and pins together. It prints each result immediately, along with the measurement-start timestamp. A result is marked invalid when the pulse is missing or falls outside the demonstration's selected 2–400 cm acceptance range.
struct SensorPins {
const char *name;
byte trigger;
byte echo;
};
const SensorPins sensors[] = {
{"Right", 3, 2},
{"Left", 4, 5},
{"Front", 7, 8}
};
const byte sensorCount = sizeof(sensors) / sizeof(sensors[0]);
const unsigned long timeoutUs = 30000UL;
const unsigned long quietTimeMs = 65UL;
bool measureCm(const SensorPins &sensor, float &cm) {
digitalWrite(sensor.trigger, LOW);
delayMicroseconds(2);
digitalWrite(sensor.trigger, HIGH);
delayMicroseconds(10);
digitalWrite(sensor.trigger, LOW);
unsigned long echoUs = pulseIn(sensor.echo, HIGH, timeoutUs);
if (echoUs == 0) return false;
cm = echoUs * 0.0343f / 2.0f;
return cm >= 2.0f && cm <= 400.0f;
}
void setup() {
Serial.begin(9600);
for (byte i = 0; i < sensorCount; ++i) {
pinMode(sensors[i].trigger, OUTPUT);
pinMode(sensors[i].echo, INPUT);
digitalWrite(sensors[i].trigger, LOW);
}
}
void loop() {
for (byte i = 0; i < sensorCount; ++i) {
unsigned long startedAtMs = millis();
float cm = 0.0f;
bool valid = measureCm(sensors[i], cm);
Serial.print(startedAtMs);
Serial.print(" ms | ");
Serial.print(sensors[i].name);
Serial.print(": ");
if (valid) {
Serial.print(cm, 1);
Serial.println(" cm");
} else {
Serial.println("INVALID");
}
delay(quietTimeMs);
}
}
The sensor order is right, left and front, matching the original function calls. The output is deliberately labeled instead of printing three anonymous numbers separated by dashes. A timestamp and a name make it much easier to identify stale data or a swapped connection.
What changed from the original sketch?
The original loop triggered the next sensor immediately after reading the previous one and used a default echo wait. The revised example adds a finite timeout, an acoustic quiet interval and separate validity. It also removes unused distance variables and avoids representing a failed measurement as an obstacle at zero centimeters.
Arduino's pulseIn documentation describes the microsecond duration and timeout result. The code's 30 ms timeout and 65 ms post-measurement interval are explicit choices for this demonstration, not universal timing recommendations for all ultrasonic products.
Calculate the Update Rate
Each acquisition includes a pulse measurement, serial-output work and a 65 ms pause. Ignoring small overheads, three near-instant valid returns still require roughly 195 ms of pauses for one complete round. That limits each sensor to around five updates per second before accounting for the other work.
If all three measurements wait approximately 30 ms before timing out, the round includes about 90 ms of waiting plus 195 ms of quiet intervals, or roughly 285 ms before serial and program overhead. The actual period is variable because echo duration depends on the response.
At a robot speed of 0.4 m/s, 285 ms corresponds to about 11.4 cm of motion. This calculation is only the distance traveled during acquisition time; braking, motor response and decision delays add more. A navigation threshold should therefore not be selected solely because the display looks responsive.
The three values are not simultaneous
By the time the front measurement is available, the right measurement is already older. On a stationary bench this may be unimportant. During a turn or rapid movement, combining the readings as though they describe one instant can create a misleading picture of the surroundings.
Keep a timestamp with each stored reading. Before using it, calculate its age and apply an application-specific freshness limit. A reading that was valid when obtained can still be too old for the current decision.
Test One Sensor Before Testing the Group
- Connect only the right sensor and verify its target response with the single-sensor method.
- Repeat for the left and front sensors using their actual assigned pins.
- Connect all three while keeping the targets stationary.
- Run the sequential sketch and confirm that each printed name matches the physical direction.
- Compare each channel's behavior with its single-sensor result.
- Change one target at a time and look for unexpected changes on another channel.
- Increase spacing or adjust mounting if cross-channel effects appear.
- Only then begin experiments with movement and application decisions.
Covering or disconnecting a sensor should not cause its previous valid number to masquerade as a fresh measurement. With the printed sketch, each failed acquisition is labeled INVALID. An application that stores the last valid result should store its age and current validity separately.
Use consistent targets
Begin with large, flat surfaces facing the relevant sensor. Changing angle, distance and material at the same time makes it difficult to distinguish crosstalk from an ordinary weak reflection. Keep a record of the physical arrangement alongside the serial log.
A test inside a corridor can behave differently from the same sensors in open space because the walls support additional reflection paths. Likewise, successful testing with stationary objects does not establish performance while the chassis vibrates or turns.
Use Left and Right Distances Carefully
The original article mentioned following a corridor between two walls. Under a simplified geometry, left and right distances can estimate lateral position. Assume the sensors point perpendicular to parallel walls, their separation is s, and the measured distances from their faces are dL and dR.
The estimated corridor width is W = dL + s + dR. For dL = 45 cm, dR = 35 cm and s = 20 cm, W is 100 cm. The center displacement toward the right is (dL − dR)/2 = 5 cm under those assumptions.
If the sensors are angled, the measured ranges follow different paths and that simple geometry no longer applies directly. If one reading is stale or invalid, the calculated center error is also unreliable. A controller should not feed every printed number into a PID calculation without checking those conditions.
PID is a later control-design step
A proportional correction reacts to current error, an integral term accumulates error over time, and a derivative term reacts to change. Their usefulness depends on the robot's dynamics and the measurement quality. Sensor noise can strongly affect a derivative estimate, while irregular sample periods complicate both integral and derivative calculations.
Before tuning gains, establish the steering direction, output limits, valid measurement conditions and a measured time interval. A timing-aware controller needs the actual elapsed time, not an assumed constant based on the delay statement alone. This article provides the sensing foundation rather than claiming a complete wall-following controller.
Prioritize Measurements According to the Task
A simple round-robin sequence gives every sensor one turn. A different task might require front measurements more frequently than side measurements. Such a schedule can be useful, but it must still leave enough acoustic separation and track the age of less frequently sampled channels.
Adding a fourth or fifth module also lengthens the cycle if the same sequential method is retained. More directional coverage trades against update rate, power, wiring and opportunities for interference. Calculate that trade before assuming that an unlimited number of sensors can be added by copying one function call.
When a nonblocking design is appropriate
The printed sketch blocks during pulse measurement and quiet intervals. A more responsive application can represent idle, trigger, waiting-for-rise, waiting-for-fall and quiet-time as explicit states, using timestamps and suitable edge capture. That allows other tasks to run between events.
Nonblocking software does not remove the acoustic quiet-time requirement. It lets the processor do other work while waiting. Likewise, an interrupt-based Echo measurement can improve timing organization without making two simultaneous transmitters acoustically distinguishable.
Filter Each Channel Separately
Maintain a separate history for left, right and front. Averaging one reading from each direction produces a number with no clear geometric meaning. If a filter spans several acquisitions, record its effective age and avoid treating an old filtered value as an immediate observation.
Do not average timeout zeros into valid distances. For example, values of 60, 61 and an invalid zero would average to about 40.3 cm, inventing an apparent closer obstacle. Keep invalid attempts as missing information and apply a stated policy for insufficient valid samples.
A median can reduce isolated outliers but cannot guarantee that the remaining reflection belongs to the intended object. Use filtering after basic interface and placement problems have been addressed, not as a way to hide a consistently unreliable channel.
Measure whether a change actually helps
When adjusting the quiet interval or mounting, keep the number of acquisition attempts fixed. For example, compare one hundred attempts per channel before and after the change, with the same target arrangement. Record the fraction of valid results and the spread of distances instead of comparing two conveniently selected screenshots.
If eighty of one hundred attempts are valid, the observed valid-result rate is 80%. That number describes this test under these conditions. It does not establish an 80% success probability in every corridor or at every robot speed. Repeat the test when an important operating condition changes.
Also compare accuracy against a known reference. A modification that makes every reading stable at the wrong distance has improved apparent repeatability while leaving a measurement error. Record both the deviation from the reference and the invalid count so the distinction remains visible.
Preserve raw observations during development
For a more detailed log, temporarily include the measured echo duration with the sensor name and timestamp. Keep diagnostic output short enough that printing does not dominate the acquisition schedule. If you change the baud rate to accommodate a larger log, update the terminal setting and measure the resulting loop timing again.
Troubleshooting and Review
| Symptom | Investigation |
|---|---|
| Works alone but fails in the group | Acoustic overlap, supply capacity and mounting |
| Moving one target changes another channel | Cross-channel reflections or swapped labels |
| Robot reacts late | Complete scan period and reading age |
| One channel always reports invalid | Its individual pins, supply and target path |
| Distances seem correct but steering is reversed | Physical direction labels and controller sign |
The main lesson is that each measurement needs an identity, a validity state and a time. Three unlabeled numbers are not yet a dependable sensing system. Keeping those pieces of information together makes later navigation logic easier to understand and diagnose.
For simulation practice, revisit the ultrasonic Proteus examples. Their extra analog controls are useful for exercising program decisions, but they should not be assumed to reproduce crosstalk between real acoustic transducers.
Frequently Asked Questions
Can all three sensors share one trigger wire?
That would trigger them together in a basic arrangement and make acoustic interference harder to control. This tutorial uses independent trigger lines and sequential requests.
Can I connect all Echo pins to one Arduino pin?
No, not directly. They are driven outputs and can conflict. The example keeps separate inputs; a different multiplexed design needs its own electrical interface.
Does the quiet delay completely eliminate crosstalk?
No. It reduces overlap, but the physical environment and mounting still matter. Compare individual and grouped operation under realistic conditions.
Why is the front reading newer than the right reading?
The program measures right first and front last. Sequential acquisition produces readings from different times, which the timestamps make explicit.
Can I use these readings directly for autonomous motion?
They are a starting point. Motion control also needs freshness limits, invalid-data behavior, suitable response timing and testing of the complete system.
Hello,
Can you please mail me the code along with explanation.
Thank You in advance
1 reply
The code is given in the post along with the download link. You can download it easily.
2 replies
I actually need the explanation along the code. So if you could also explain the code line wise i would be grateful you.
1 reply
Code isn't much difficult, give it time n then ask questions.
1 reply
sir, can u help me with arduino coding
Hi
Syed Zain Nasir please can you help about above project code if there are 4 ultrasonic sensors and connected with LCD for measuring distance (cm)?
hello. Can I ask? I would like to apply to your coding to combine the left and front sensor using OR(||), so if a person pass by this 2 sensor, it will light up the LED to give a high. How do I do that? Any example?
Hello. Your coding is awesome. I finally found what I need. But, how do I implement the codes were by the front and left sensor can detect the distance and then light up the LED. Can you help me with this? I have tried many ways to modify the codings but it is not reading the codes
1 reply
Contact us via Skype n we will help you out.
i have interfaced a single ultrasound sensor(hcsr04) and got correct measurement of the distance no problem.
But when there is no object then too the led's display some huge value (may be the max limit of the sensor i.e 400cm)
I have written code in 8051 c language.
did u get the same problem?
one point to say that the ceiling clearance in about 3m from the sensor so that it might detect..as i guess
here is the code for two sensor interface
i have not called the function twice.
But i would like to discuss on logic what i have written in order to detect two sensors interface
and here is the code only a part of main code and not any initialization or delay subroutines shown
1)while(1)
2){
3)trig1=1;
4)trig2=1;
5)delay(1);
6)trig1=0;
7)trig2=0;
8)while(echo1==0&&echo2==0);
9)TR0=1;
10)while(echo1!=0||echo2!=0);
11)TR0=0;
12)DPH=TH0;
13)DPL=TL0;
14)if(DPTR<30000)
15) range=DPTR*0.01847091;
16)else
17) range=0;
18)if(range<100)
19)P2=range;
20)else
21)P2=0X00;
22)leddelay(999);
23)}
line no 10 is the one i would like to discuss.
in this i have checked for which of the two sensors go low at first whether the left or right whichever goes low first the distance is calculated and checked if within the max limit if not within the max limit then no object detected.
if say left sensor goes low first then robot should turn left first otherwise right.
But if both sensor go low together that means object right in front of the robot hence can move accordingly. Is this logic ok?
Salam brother Syed Zain Nasir
thank you for your informative tutorial. I need to use similar case to control my robot to avoid obstacles. I also have three ultrasonic sensors. Just in your code how I can know if the distance is related to left sensor so a robot can turn right for example or for right sensor or even for front sensor.
Many thanks in advance
Hello .I met some problem with HC-SR 04 . Could you give me a hand?
does it possible use Multiple Ultrasonic Sensor to communicate each others ?
Ex : A ,B two sensors
A trig and B echo
not A trig A echo B trig B echo ...etc
the result that i get always B trig & B echo.
A never do any work. ..
Dear Syed,
We are a group of students from the Netherlands, end working on an autonomic wheelchair. we are using your guide for multiple ultrasonic censors as an part for the project. the problem we encountered is that, if we use more than three ultrasonic censors. the system is way too slow to use, and become even slower when the distant increases.
we want the program to print the values in the monitor. do you have any idea's what the reason is and how we eventually can solve it.
we thank you for your guide and hope you can help us out with this one.
1 reply
Add me on Skype and I will check it out. My Skype id is "theenggprojects". Thanks.
I have only two ultrasonic sensor so which parts of the coading have to be changed
1 reply
Simply remove the code for third sensor. That's quite easy.
1 reply
hello sir . i already simply move the third code sensor but still the second sensor did not function . can u explain the problem ??
can all trigger pin just connected to one pin only?
1 reply
I just wanted to ask the same question. I think it would be possible to connect all triggers to one common pin and then process signal just from appropriate echo pin. Has anybody tested it? ?
1 reply
No, its not possible. When you trigger from same pin then you can't get all the echo pins at the same time. So, use separate pins.
1 reply
Why cannot you use one trigger, but separate echo pins? You trigger all the senders at the same time, but you read only the echo that you want, it should save some wiring, and the code is a little simpler as well.
Hey. I'm doing a project which also involves 2 Ultrasonic Sensors. My problem is that every time I try on running both sensors simultaneously I always get a "0" distance in one of the sensors. The first thing that I hypothesized is that the power in my arduino isn't enough to drive both Ultrasonic sensors, but according to all my research regarding the problem, the arduino shouldn't have a problem with driving 2 US. What do you think could be the problem in my project? Should I not position the sensors side by side in order for the pulse of one sensor interferes with the echo of the other sensor? I'm stuck with this problem. Any feedback from you would be greatly appreciated. Thank you!
Hello..we have a project using srf-04..The set up is almost the same to yours removing the rightmost sensor. We are able to measure distance . However, for initial set up, they must have same distance to be measured..but the reading has difference( for e.g. 2cm for the first sensor while 5.06 cm to the other one) and they keep on changing..Also, the sensor are measuring negative values for distance. Both sensor are touching the tube with 1 cm diameter..Why is the sensor gives inaccurate measurement? Thank you :)
1 reply
same with me. i use 2 hc-sr04 then it not work together and the second sensor give the negative value.
1 reply
Same here, help please.
can i add 1 additional sensor, 4 LEDs on each sensor as indicator, 1 LCD display and buzzer? do the connections on arduino would be enough? PLEASE HELP. Thank you so much. :)
Hey, if not measuring distance but just for motion detection, can I switch ON all the Sensors at the same time to increase the directivity of detection? will there be any issue related to interference?
AOA.
Bro I am working in project i.e robot car that follow beacon. You are too intelligent and i need your help. Email me so that i could reach u.
1 reply
Hi,
Kindly add me on Skype and we will discuss it out. My Skype id is theenggprojects.
Thanks.
Can you Display Out put on a Web page or Using C#, .Net .If You can plz tell me how . I'm Trying to make IOT Garbage Monitoring using IOT . So I want to display Levels of garbage on each dustbins on a webpage ....Can you help me
Hello
can you help me to built the same hardware but with esp 8266 code not arduino ??
I'm doing a smart belt for blind with 3 ultrasonic sensors as left right and front, in addition to that I'm using one more sensor in form of smart stick...and I'm using simple vibration motor or buzzer for sensor output... help me with the connection and code

























Comments
38