PIR sensor with Relay and timing


Again i need some help on a smal piece of code.

Using a PIR sensor it outputs HIGH when there is a movement. But after "time delay" set on the sensor it outputs LOW even if there is movement. Than while its LOW it take a few seconds to notice movement again and sets output to HIGH.

I'm trying (in de code) to check: when the PIR outputs LOW to delay 5 seconds and check the status of the output again. And if it it still LOW (after 5 seconds) then set the relay to LOW. But if the state of the PIR after 5 seconds is HIGH again do nothing (keeping Relay HIGH).

Below you can see my code using millis but somehow as soon as PIR goes to LOW my relay also instantly goes to LOW. And i don't understand why?

Any comment or help is welcom.

tnx N

unsigned long startMillis;
unsigned long currentMillis;
const unsigned long period = 5000;

#define relais D5
#define pirsensor D2
int pirsensorstate;

void setup() {
  pinMode(pirsensor, INPUT);
  pinMode(relais, OUTPUT);

void loop()
  pirsensorstate = digitalRead(pirsensor);

  if (pirsensorstate == 1) {
    digitalWrite(relais, 1);

  if (pirsensorstate == 0) {
     currentMillis = millis();
    if (currentMillis - startMillis >= period) {
      pirsensorstate = digitalRead(pirsensor);
      if (pirsensorstate == 0) {
        digitalWrite(relais, 0);
        startMillis = currentMillis;

You should only get a value for startMillis when the pin first goes LOW. See the state change example for help with that.

You do know you can change that behavior on most PIR's? Called "retrigger" or "repeat trigger".

septillion: You do know you can change that behavior on most PIR's? Called "retrigger" or "repeat trigger".

This PIR sensor has a jumper for it but it does not work 100%. Thank for your input.