digitalWrite for a period (not delay)

Hello guys,

I have a question regarding an output digital pin which will be connected a led.

I do not want to use delay because during the “blinking” in case another reading will be process i want to start again the “blinking”. Bellow i am writing my code for understanding.

Thanks in advance

const unsigned int TRIG_PIN=13;
const unsigned int ECHO_PIN=12;
const unsigned int BAUD_RATE=9600;
bool ledState = false;

void setup() {
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
pinMode(8, OUTPUT);
Serial.begin(BAUD_RATE);
}

void loop() {
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);

const unsigned long duration= pulseIn(ECHO_PIN, HIGH);
int distance= duration/29/2;
if(duration==0){
Serial.println(“Warning: no pulse from sensor”);
}
else{
Serial.print(“distance to nearest object:”);
Serial.println(distance); Serial.println (" cm");
}
delay(500);
//check the distance.
if (distance <= 20){
digitalWrite (8, HIGH);
delay (10000); //in this section i want to proceed another reading… for example if other object will be in front of the sensor after 2-3 or 4 secounds.
//but in this case, entire code has a 10 secounds freez
}
else{
digitalWrite (8, LOW);
}

Please review the Blink without delay example in the IDE, it should cover everything you need to know.

Take a look at Using millis() for timing. A beginners guide, Several things at the same time and the BlinkWithoutDelay example in the IDE