# How to use two Sonar's

I'm using a single sonar, but I want to use two sonar to know another distance.

Here is how I use my single sonar:

``````    #include <NewPing.h>

#define TRIGGER_PIN  9
#define ECHO_PIN  10
#define MAX_DISTANCE  100 // in CM
...
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);
...
delay(100);
unsigned int uS = sonar.ping();
int cm = uS / US_ROUNDTRIP_CM;
``````

But I Want to use a second one to calculate another distance, how to?

``````#define TRIGGER_PIN_2  11
#define ECHO_PIN_2  12
...
new NewPing sonar(TRIGGER_PIN_2, ECHO_PIN_2, MAX_DISTANCE);
...
???
``````

EDIT:

Maybe this one, I'll try this when I will get my second sonar

``````#define SONAR_NUM     2
#define MAX_DISTANCE 200
...
NewPing sonar[SONAR_NUM] = {
NewPing(9, 10, MAX_DISTANCE),
NewPing(11, 12, MAX_DISTANCE)
};
...
delay(100);
unsigned int uS1 = sonar[0].ping();
int cm1 = uS1 / US_ROUNDTRIP_CM;

unsigned int uS2 = sonar[1].ping();
int cm2 = uS2 / US_ROUNDTRIP_CM;
``````

Maybe this one, I'll try this when I will get my second sonar

Ding ding ding! Yeah, this would be one way to do that. That creates an array so you can reference the sonar with `sonar[i]`, where `i` is either 0 or 1 for the first or second number.

For only two sensors, it might be easier just to do something like this:

``````NewPing sonar1(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);
NewPing sonar2(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);
``````

Then you can run the other code like this:

``````delay(100);
unsigned int uS1 = sonar1.ping();
int cm1 = uS1 / US_ROUNDTRIP_CM;

unsigned int uS2 = sonar2.ping();
int cm2 = uS2 / US_ROUNDTRIP_CM;
``````

A little less code to read, whichever one you want.

The reason you can do this is you can replace the `sonar` with whatever you wanted (following C++ variable rules like no spaces, etc.). You could call it `Arduino_Sonar` if you wanted to.

The array is basically a simple way of grouping variables together easily. It's not convenient to declare 500 differently name variables; I can just do `int numbers[500];` to declare them. An array might be more useful if you're expanding your circuit, but either is correct.

• @Annonomous : Thanks, What a great price! I prefer your version, only two sonar's :-) Thanks for the support! Jul 24 '14 at 12:39