So one thing about the simulations, they don't account for resetting everything if the motion stops and then resumes while light is already on. Basically if the person stands still for a few seconds you don't want to kill the lights.
Set your sensor to whatever you think a good time delay is (I just set it to the minimum pot setting) and make sure it is jumpered for continuous mode. Then use a State Machine code model as has been suggested. Here is a simple first pass with not much frill:
// Sketch simulates turning a light on or off based on motion sensor using the onboard LED as the light
const int LED_PIN = 13; // LED on Pin 13 of Arduino
const int PIR_PIN = 7; // Input for HC-S501
//Defines for sensor states to make switch logic clear
#define noMotionDetected LOW
#define motionDetected HIGH
//Define elapsedMillis to read a value of millis and subtract the millis reading from when the timer was fist started
#define elapsedMillis millis() - startTimeMillis
//Declare a const for the light off delay value in millis once no motion is detected
const int LIGHT_OFF_DELAY = 5000;
//Declare variables
unsigned long startTimeMillis = 0;
int pirValue = 0;
bool isLightOffTimeActive = false;
bool isLightOn = false;
void setup() {
pinMode(LED_PIN, OUTPUT);
pinMode(PIR_PIN, INPUT);
digitalWrite(LED_PIN, LOW);
Serial.begin(9600);
}
void loop() {
//Read the current sensor value
pirValue = digitalRead(PIR_PIN);
switch(pirValue)
{
case motionDetected:
//An LED you could just always turn on every loop but real lights you probably don't want to pulse the switch
//so use a boolean
if(!isLightOn)
{
digitalWrite(LED_PIN, HIGH);
isLightOn = true;
}
// Time flag could be active because a person was moving then stood still then moved again.
// As long as we have motion, reset the time flag to keep the lights on
isLightOffTimeActive = false;
break;
case noMotionDetected:
//If both isLightOn and !isLightOffTimeActive this is our first pir LOW after motion so start the time
if((isLightOn) && (!isLightOffTimeActive))
{
isLightOffTimeActive = true;
startTimeMillis = millis();
}
else
{
//If light is on also evaluate the timer
if((isLightOn) && (elapsedMillis >= LIGHT_OFF_DELAY))
{
// Turn off light and reset
digitalWrite(LED_PIN, LOW);
isLightOn = false;
isLightOffTimeActive = false;
startTimeMillis = 0;
}
// Else do nothing, sensor is LOW but either time has not elapsed yet or time flag and light are off.
}
break;
default:
//Should not hit this but do nothing
Serial.println("Hit default");
break;
}
}