Im working on a arduino project for school and I cant get it so that a led turns on when an object is detected by 2 ultrasonic sensors and another led light would light up if the object is detected by only 1 ultrasonic sensor. the problem is that the led for 2 ultrasonic sensors is turned on even with no object in front of either ultrasonic sensor. I have been searching for answers but I could not find any information on the internet.
// defines pins numbers
// ledpin1 is red, ledpin2 is green
const int trigPin = 10;
const int echoPin = 9;
const int ledPin = A4;
const int ledPin2 = A5;
const int ledPin3 = A3;
const int trigPin2 = 12;
const int echoPin2 = 11;
//remember to define led pin2
// defines variables
long duration;
long duration2;
int distance;
int distance2;
int safetyDistance;
int safetyDistance2;
void setup() {
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
pinMode(ledPin, OUTPUT);
pinMode(ledPin3, OUTPUT);
pinMode(ledPin2, OUTPUT);
pinMode(trigPin2, OUTPUT);
pinMode(echoPin2, INPUT);
Serial.begin(9600); // Starts the serial communication
}
void loop() {
//SENSOR1
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculating the distance
distance= duration*0.034/2;
safetyDistance = distance;
//SENSOR2
// Clears the trigpin2
delay(200);
digitalWrite(trigPin2, LOW);
delayMicroseconds(2);
//Sets trigPin2 high for 10ms
digitalWrite(trigPin2, HIGH);
delayMicroseconds(2);
digitalWrite(trigPin2, LOW);
// Reads the echopin2
duration2 = pulseIn(echoPin2, HIGH);
//distance calculation
distance2= duration2 * 0.034/2;
if (safetyDistance <=30 || safetyDistance2 <=30)
{
digitalWrite(ledPin3, HIGH);
digitalWrite(ledPin2, LOW);
digitalWrite(ledPin, LOW);
}
else{
digitalWrite(ledPin2,HIGH);
digitalWrite(ledPin, LOW);
digitalWrite(ledPin3, LOW);
}
}