HEY! I was trying to get 2 HC-SR04 to work together, such that i get the average of the 2 readings. but it doesnt work as expected and only displays 'OUT OF RANGE' on serial monitor. please help
this is my code:
#define echo2 8
#define trig2 9
#define LED1 2 // LED pin 2
#define echo 13 //ECHO pin 13
#define trig 10 //TRIG pin 10
float duration, distance, duration2, distance2, avg; //float command helps us to determine value of duration and distance in decimals
void setup() {
Serial.begin (9600); // setup ¯\_(ツ)_/¯
pinMode (echo, INPUT);
pinMode (trig, OUTPUT);
pinMode (LED1, OUTPUT);
pinMode (echo2, INPUT);
pinMode (trig2, OUTPUT);
}
void loop() {
digitalWrite (LED1, LOW);
digitalWrite (trig, LOW);
digitalWrite (trig2, LOW);
delayMicroseconds (2);
digitalWrite (trig, HIGH);
digitalWrite (trig2, HIGH);
delayMicroseconds (10);
digitalWrite (trig, LOW);
digitalWrite (trig2, LOW);
duration = pulseIn(echo ,HIGH);
duration2 = pulseIn(echo2 , HIGH);
distance = (duration/2) * 0.0343;
distance2 = (duration2/2) * 0.0343;
avg = (distance2/2 + distance/2);
Serial.print ("Distance = ");
if (avg>=400 || avg<=2) { // the formula of distance is duration of impulse divided by 2 multipled by speed of light in air meter per sec
Serial.println ("OUT OF RANGE");
digitalWrite (LED1, HIGH);
delay(50);
digitalWrite(LED1,LOW);
}
else {
Serial.print (avg);
Serial.println("cm");
delay (150);
}
delay (150);
}
Comments
1 year ago
I don't have time to analyse your code in detail but, at first glance, it looks like you're triggering one HC-SR04 then triggering the other then waiting for a reply from each one. That won't work
They'll hear each other's echos. You must trigger one, wait for it's echo (i.e. the first echo it hears) then wait at least 10-20mSec for all the other echos from the room to die away then trigger the second HC-SR04 and waits for its echo.
If both HC-SR04s are pointing in the same direction, you won't get any benfit from having the second one. Search https://forum.arduino.cc for "multiple HC-SR04".