I'm new to Arduino and I currently have a project that involves the control of an LED via ultrasonic sensor. Basically, if an object passes through the ultrasonic sensor, the LED will be ON for 5 seconds but adding another set of LED and ultrasonic sensor with the same function gives a problem because the other LED won't light up if the other one is ON and vice versa because of the delay whereas what I want is to be able to make them both light up and stay lit for 5 seconds after their respective ultrasonic sensors detect an object. I've tried using the "Blink without delay" example but I can't understand it nor make it work. Please help me guys and thanks for reading. Here is my current code:
int trigPin1=2;
int echoPin1=3;
int trigPin2=4;
int echoPin2=5;
int led1=10;
int led2=11;
void setup() {
Serial.begin(9600);
pinMode(trigPin1, OUTPUT);
pinMode(echoPin1, INPUT);
pinMode(trigPin2, OUTPUT);
pinMode(echoPin2, INPUT);
pinMode(led1,OUTPUT);
pinMode(led2,OUTPUT);
}
void loop() {
long duration1, distance1;
digitalWrite(trigPin1, LOW); // Added this line
delayMicroseconds(2); // Added this line
digitalWrite(trigPin1, HIGH);
delayMicroseconds(10); // Added this line
digitalWrite(trigPin1, LOW);
duration1 = pulseIn(echoPin1, HIGH);
distance1 = (duration1/2) / 29.1;
if (distance1 >= 500 || distance1 <= 0){
Serial.println("Out of range");
}
else {
Serial.print ( "Sensor1 ");
Serial.print ( distance1);
Serial.println("cm");
}
long duration2, distance2;
digitalWrite(trigPin2, LOW); // Added this line
delayMicroseconds(2); // Added this line
digitalWrite(trigPin2, HIGH);
delayMicroseconds(10); // Added this line
digitalWrite(trigPin2, LOW);
duration2 = pulseIn(echoPin2, HIGH);
distance2= (duration2/2) / 29.1;
if (distance2 >= 500 || distance2 <= 0){
Serial.println("Out of range");
}
else {
Serial.print("Sensor2 ");
Serial.print(distance2);
Serial.println("cm");
}
if(distance1>20 || distance2>20){
digitalWrite(led1,LOW);
digitalWrite(led2,LOW);
}
else if(distance1<20){
digitalWrite(led1,HIGH);
delay(5000);
}
else if(distance2<20){
digitalWrite(led2,HIGH);
delay(5000);
}
}