Using a HC-SR501 PIR to detect movement.

This PIR sketch detects movement in a room and prints a message to the Serial Monitor as well as sounding a buzzer. The Arduino pin used to drive the buzzer could just as easily drive a LED or a relay.

The layout is shown below, a small speaker is connected between Gnd and pin 10. The PIR unit has three connections, connect Vcc to the Arduino 5volts , Gnd to Arduino Gnd and the signal output to Arduino pin 2.

void loop(){
val = digitalRead(inputPin); // read input value
if (val == HIGH) { // check if the input is HIGH
blinky(); // blink LED when motion haas been detected
//digitalWrite(ledPin, HIGH); // turn LED ON
playTone(300, 160);
delay(150);
if (pirState == LOW) {
// we have just turned on
Serial.println("Motion detected!");
// We only want to print on the output change, not state
pirState = HIGH;
}
}
else {
digitalWrite(ledPin, LOW); // turn LED OFF
playTone(0, 0);
delay(300);
if (pirState == HIGH){
// we have just turned off
Serial.println("Motion ended!");
// We only want to print on the output change, not state
pirState = LOW;
}
}
}