How do you use 2 ultrasonic sensors simultaneously?

I am looking to use 2 ultrasonic sensors(HC-SRO4 modules) to measure in centimeters simultaneously. I have no syntax errors or compiling errors but only one ultrasonic sensor is giving an output rather than both. Can someone let me know why this is happening?
My code can be found below:

#include <NewPing.h>
NewPing sonar [2] = {
   NewPing(31, 30, 70), // Each sensor's trigger pin, echo pin, and max distance to ping. 
   NewPing(32, 33, 70),
};
void setup() {
  Serial.begin(9600);
  

}

void loop() {
 Serial.print("Distance:");
 Serial.print(sonar[1].ping_cm());
 Serial.print(" cm.");
 Serial.print("==>");
 Serial.print(sonar[2].ping_cm());
 Serial.print(" cm.");
 delay(1000);
}

Thank you for your help!

Welcome to the forum

Arrays in C start from 0, not 1 so your sensors are sonar[0] and sonar[1], not sonar[1] and sonar[2]

Thank you for your help. It worked.

I am glad to hear it. Note, however, that the sensors may pick up signals from one another

Good luck going forward

This means you have to wait maybe half a second to let fade away the "PING" of the last measuring before you start the PING of the second.

This especcially applies of both sensors are sending in the same direction
best regards Stefan

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.