LED Delay On with Motion Sensor.

Hello everyone! I am a newbie, and I picked up Arduino for my project. Basically, what I want the code to do is:

ON> Delay 5 sec, OFF. But it will pause if motion is detected, and then continue when there is no more motion. What i have now for MS OFF is:

//what i want: delay on, run. if motion detected, off.

int led = 13;       
int sensor = 2;             
int state = HIGH;             // by default, no motion detected
int val = 0;                

void setup() {
  pinMode(led, OUTPUT);      // initalize LED as an output
  pinMode(sensor, INPUT);    // initialize sensor as an input
  Serial.begin(9600);       
}

void loop(){
  val = digitalRead(sensor);   
  if (val == HIGH) {         
    digitalWrite(led, LOW);   
    delay(5000);                
    
    if (state == LOW) {
      Serial.println("Motion detected!"); 
      state = HIGH;       // update variable state to HIGH
    }
  } 
  else {
      digitalWrite(led, HIGH); // turn LED ON
      delay(20);             // delay 
      
      if (state == HIGH){
        Serial.println("Motion stopped!");
        state = LOW;      
    }
  }
}

I was planning to add this following code for the LED Delay Off into the IF loop, but it doesn't really work. Could someone please help me? I am reading up on Millis too but I'm not sure how to proceed.

int led = 13;             
void setup() {
    pinMode(led,OUTPUT);
    digitalWrite(led,HIGH);
    delay (10000);
    digitalWrite (led,LOW);
} 
void loop() {
}

Hello
I´ve tried to understand the logic of your sketch.
The following question arose:
In which cases and why do you need a delay, how ever performed, for the data processing ?

paulpaulson:
Hello
I´ve tried to understand the logic of your sketch.
The following question arose:
In which cases and why do you need a delay, how ever performed, for the data processing ?

Hello Paulpaulson,

My device is a UVC lamp. UVC is harmful to humans so I wanted it to have a delay after ON so the user will have time to place the lamp in the cupboard/ close the doors before it runs. Ofc, the motion sensor could be a way to prevent it, but I want it to be safer.

Does this answer your question?

Hello
Yes , it did, many thanks.
Please stay tuned. Today I´ll take a look in my sketch box to find a proper solution.

PM sent

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