Hello,
I am trying to run three sonar sensors by an arduino. Basically for detecting obstacle (front, left and right). My code and circuit diagram is attached.
Problem is, first two sonar works. But the output of 3rd one is always 0 distance. I have changed place of sonar sensor(SR04). All three of them works independently. The third sonar connected always outputs high when i upload my code.
Hopefully i have properly stated my problem. I want to know how to make these three sonar work together. Thank you.
#define ledPin 8 //these are the led pins
#define ledPin2 9
#define ledPin3 13
class Sonar{
public:
int triggerPin;
int echoPin;
long distance, duration;
void sonar(int trig, int echo){ //custom initializer
triggerPin = trig;
echoPin = echo;
pinMode(triggerPin, OUTPUT);
pinMode(echoPin, INPUT);
}
bool isObstaclePresent(Sonar s){ //checking an obstacle is within less than or equal five centimeters
digitalWrite(s.triggerPin, LOW);
delayMicroseconds(2);
digitalWrite(s.triggerPin, HIGH);
delayMicroseconds(10);
digitalWrite(s.triggerPin, LOW);
duration = pulseIn(s.echoPin, HIGH);
duration /= 29; //for converting miliseconds to centimeters
duration /= 2; //for getting the actual distance
distance = duration;
if(distance <= 5){ //checking if the distance is less or equal five
return true;
}
else{
return false;
}
}
};
Sonar sonar1;
Sonar sonar2;
Sonar sonar3;
void setup() {
// put your setup code here, to run once:
sonar1.sonar(2, 4); // sonar(trig, eho);
sonar2.sonar(6, 7);
sonar3.sonar(11, 12);
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
if((sonar1.isObstaclePresent(sonar1) == true) ){ //checking the obstacle for sonar1
pinMode(ledPin,OUTPUT);
digitalWrite(ledPin,HIGH);
}
else digitalWrite(ledPin,LOW);
if((sonar2.isObstaclePresent(sonar2) == true)){
pinMode(ledPin2,OUTPUT);
digitalWrite(ledPin2,HIGH);
}
else digitalWrite(ledPin2,LOW);
if((sonar3.isObstaclePresent(sonar3) == true) ){
pinMode(ledPin3,OUTPUT);
digitalWrite(ledPin3,HIGH);
}
else digitalWrite(ledPin3,LOW);
Serial.print("this is for sonar1: ");
Serial.println(sonar1.distance);
Serial.print("this is for sonar2: ");
Serial.println(sonar2.distance);
Serial.print("this is for sonar3: ");
Serial.println(sonar3.distance);
}
sonar3.ino (2.05 KB)