# How to hold output for 10 seconds?

I am using Ultrasonic sensor, LED, and buzzer in my circuit. However, I need the LED to stay on for like 10 seconds or more.

Here is my code

``````const int trigPin = 9;
const int echoPin = 10;
const int buzzer = 11;
const int ledPin = 13;

long duration;
int distance;
int safetyDistance;

void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(buzzer, OUTPUT);
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
}

void loop() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);

digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);

duration = pulseIn(echoPin, HIGH);

distance = duration * 0.034 / 2;

safetyDistance = distance;
if (safetyDistance <= 5) {
digitalWrite(buzzer, HIGH);
digitalWrite(ledPin, HIGH);

}
else {
digitalWrite(buzzer, LOW);
digitalWrite(ledPin, LOW);
}

Serial.print("Distance: ");
Serial.println(distance);
}
``````

If you don't mind the program doing nothing for 10 seconds then `delay(10000); ` will do what you want

If you need to do other things during the period then delay() is not the way to do it. Take a look at Using millis() for timing. A beginners guide, Several things at the same time and the BlinkWithoutDelay example in the IDE

Hello
The sketch is untestet, but well done

``````enum {Led};
const unsigned long Duration {10000};
struct TIMER {
unsigned long timeStamp;
unsigned long duration;
} timer[] {
{0,Duration},
};
const int trigPin = 9;
const int echoPin = 10;
const int buzzer = 11;
const int ledPin = 13;
long duration;
int distance;
int safetyDistance;
void startTimer (TIMER &timer) {
timer.timeStamp= millis();
}
void stopTimer(TIMER &timer) {
timer.timeStamp= 0;
}
enum {NoEvent,Event};
bool eventTimer(TIMER &timer) {
return (( millis() - timer.timeStamp >= timer.duration && timer.timeStamp)?Event:NoEvent);
}
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(buzzer, OUTPUT);
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
}
void loop() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = duration * 0.034 / 2;
safetyDistance = distance;
if (safetyDistance <= 5) {
digitalWrite(buzzer, HIGH);
digitalWrite(ledPin, HIGH);
startTimer(timer[Led]);
}
else {
digitalWrite(buzzer, LOW);

}
Serial.print("Distance: ");
Serial.println(distance);
if (eventTimer(timer[Led])) digitalWrite(ledPin, LOW),stopTimer(timer[Led]);
}
``````

It worked perfectly. Thank you!

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.