#define TRIG_PIN 2
#define ECHO_PIN 3
#define LED_PIN 4
long duration;
int distance;
bool timerPaused = false;
unsigned long previousMillis = 0;
const unsigned long interval = 5000; // 5 seconds
void setup() {
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
pinMode(LED_PIN, OUTPUT);
Serial.begin(9600);
}
void loop() {
unsigned long currentMillis = millis();
// Start timer for the first 5 seconds
if (currentMillis < interval) {
digitalWrite(LED_PIN, LOW); // Turn off the LED
timerPaused = false;
delay(100);
}
// Wait for the sensor to detect something within 30cm
else if (currentMillis >= interval && !timerPaused) {
digitalWrite(LED_PIN, HIGH); // Turn on the LED
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
duration = pulseIn(ECHO_PIN, HIGH);
distance = duration / 58;
Serial.println(distance);
if (distance > 0 && distance < 30) {
// Start timer for the second 5 seconds
previousMillis = currentMillis;
timerPaused = false;
}
else {
// Pause the timer and turn on the LED
timerPaused = true;
digitalWrite(LED_PIN, HIGH);
}
delay(100);
}
// Wait for the sensor to detect nothing within 30cm
else if (currentMillis - previousMillis >= interval && timerPaused) {
digitalWrite(LED_PIN, HIGH); // Turn on the LED
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
duration = pulseIn(ECHO_PIN, HIGH);
distance = duration / 58;
Serial.println(distance);
if (distance == 0 || distance >= 30) {
// Start the next cycle
previousMillis = currentMillis;
timerPaused = false;
}
delay(100);
}
// Turn off the LED when the timer is over
else {
digitalWrite(LED_PIN, LOW); // Turn off the LED
timerPaused = false;
delay(100);
}
}