LED blink via ultrasonic sensor

So I’m using this code perfectly fine when they are not blinking, the only the respective LED should light up at a specific distance range.

But after I added the code for blink, The LED for a specific range still blinks with the one the should be blinking on the correct range.

}

void loop() {
long duration, distance;
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1;

if (distance <= 100) {
digitalWrite(led, HIGH);
delay(200); // waits for a second
digitalWrite(led, LOW); // sets the LED off
delay(200); // waits for a second
digitalWrite(led, HIGH);
sound = 300;
}
else {
digitalWrite(led,LOW);

}
if (distance < 60) {
digitalWrite(led,LOW);
digitalWrite(led3, HIGH);
delay(100); // waits for a second
digitalWrite(led3, LOW); // sets the LED off
delay(100); // waits for a second

sound = 375;
}
else {
digitalWrite(led3, LOW);
digitalWrite(led,LOW);

}

if (distance < 20) {
digitalWrite(led5, HIGH);
delay(50); // waits for a second
digitalWrite(led5, LOW); // sets the LED off
delay(50); // waits for a second
digitalWrite(led3, LOW);
digitalWrite(led,LOW);
sound = 450;
}
else {
digitalWrite(led5,LOW);

}

if (distance > 100 || distance <= 0){
Serial.println(“Out of range”);
noTone(buzzer);
}
else {
Serial.print(distance);
Serial.println(" cm");
tone(buzzer, sound);

}
delay(500);
}

You can do a range using distance.

if (distance >= 60 && distance < 100)

Have you looked at a state machine option to do this?
Also, get rid of the delays and master the blink without delay example.

See:
http://www.thebox.myzen.co.uk/Tutorial/State_Machine.html

LarryD:
You can do a range using distance.

if (distance >= 60 && distance < 100)

Have you looked at a state machine option to do this?
Also, get rid of the delays and master the blink without delay example.

See:
State Machine

Dude thanks a lot! The distance range code helps a lot. Although I should also start studying the state machine and blink without delay. Thanks again.

Here is a good discussion also on state machines:
http://www.gammon.com.au/forum/?id=12316

Attached are two sketches that you might find useful to read.

Task_timers.ino (2.56 KB)

StateMachine.ino (4.41 KB)