Ultrasonic sensors not working together

Hello I am trying to make a completely autonomous robot using 4 HCSRO4 senors. I am using the new ping library but i am having trouble getting the code to work. it seems to be jumpy and not working at all at times. I've checked the connections and i know everything is hooked up. here is my code so far.

#include <Servo.h>

#include <NewPing.h>

#define TRIGGER_PIN 53
#define ECHO_PIN 52
#define MAX_DISTANCE 300
#define TRIGGER_PIN2 50
#define ECHO_PIN2 51
#define MAX_DISTANCE2 200

Servo BackLeft;
Servo BackRight;
Servo FrontLeft;
Servo FrontRight;
int loopCounter;

NewPing sonar (TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // SETUP for 1st ultrasonic sensor
NewPing sonar2 (TRIGGER_PIN2, ECHO_PIN2, MAX_DISTANCE2);

void setup()
{
BackLeft.attach (2);
BackRight.attach (3);
FrontRight.attach(4);
FrontLeft.attach (5);

}
void loop ()
{
unsigned int CM1 = sonar.ping_cm();
unsigned int CM2 = sonar2.ping_cm();

if (2 < CM1 && 10 < CM2)
{
BackLeft.writeMicroseconds ( 1600);
BackRight.writeMicroseconds ( 1600);
FrontRight.writeMicroseconds ( 1600);
FrontLeft.writeMicroseconds ( 1600);
delay (100);

}
else if ( 5 > CM1 || 17> CM2)

{
if (7 > CM1 && 17 < CM2 )
{
BackLeft.writeMicroseconds ( 1500);
BackRight.writeMicroseconds ( 1500);
FrontRight.writeMicroseconds ( 1500);
FrontLeft.writeMicroseconds ( 1500);
delay(100);
}
else if (17> CM2 )
{
BackLeft.writeMicroseconds ( 1600);
BackRight.writeMicroseconds ( 1400);
FrontRight.writeMicroseconds ( 1600);
FrontLeft.writeMicroseconds ( 1400);
delay (100);
}
}
}

i know the new ping library supports multiple sensors but the example code does not seem to allow me to save each sensor to its own integer. any help would be awesome

Hi, please use code tags to post your sketch thanks.

You are pinging the sensors immediatiely after each other.

As they work on the same ultrasonic frequency and you are looking for echoes, there will be more than just one echo coming back per ping. Even though sensors are pointed in different directions echos are reflected transmissions and reflect all over the place, not just back to relevant receiver.

You have no way of knowing if echo received on second sensor is echo from first sensor transmit.
Place a delay after each sonar.ping , say 100mS for a start and see if that works.

Tom.... :slight_smile:

Hi, have you fixed the problem?
Tom... :slight_smile: