Arduino only defines one variable set, and not both.

This code essentially is having two ultrasound sensors and a photo resistor work together to activate a relay.

My problem, is in defining the distance/duration variables

duration2 = pulseIn(echoPin2, HIGH);
distance2 = (duration2/2) / 29.1;
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1;

The Arduino only calculates the first set and ignores the second set. In the serial monitor it prints the “distance2” number, but for “distance”, it only displays a 0. If I put the “distance” set first, then it is the opposite and “distance2” displays a 0.

#define trigPin 12
#define echoPin 13
#define trigPin2 10
#define echoPin2 11
int relay = 8;
int sensorPin = A0;
int sensorValue = 0;

void setup() {
Serial.begin (9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(trigPin2, OUTPUT);
pinMode(echoPin2, INPUT);
pinMode(relay, OUTPUT);

}

void loop() {
int duration, distance, sensorValue, duration2, distance2;
sensorValue = analogRead(sensorPin);
digitalWrite(trigPin, HIGH);
digitalWrite(trigPin2, HIGH);
delayMicroseconds(1000);
digitalWrite(trigPin, LOW);
digitalWrite(trigPin2, LOW);
duration2 = pulseIn(echoPin2, HIGH);
distance2 = (duration2/2) / 29.1;
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1;
if (distance >= 165 || distance <= 0 && distance2 >= 50 || distance <= 0 | sensorValue <= 900){
Serial.println(“no object detected”);
Serial.println(distance);
Serial.println(distance2);
Serial.println(sensorValue);
digitalWrite(relay, HIGH);

}
else {
Serial.println(“object detected”);
digitalWrite(relay, LOW);
Serial.println(distance);
Serial.println(distance2);
Serial.println(sensorValue);
delay (15000);
}
delay(100);
}

pulseIn is a blocking function. You triggered both pulses and then you waited in a blocking pulseIn function for the first echo. While you were doing that, the second echo also came back and you missed it. Then you call pulseIn to wait for the second echo, which has already come and gone, and it times out and gives you a 0.

You need to separate the timing of those two things.

Note: to avoid echoes from the first sensor you should wait about 30 milliseconds between the first trigger and the second.