How HC-SR501 PIR Sensor Works & How To Interface It With Arduino
How HC-SR501 PIR Sensor Works & How To Interface It With Arduino
com
8-10 minutes
Now when the PIR detects motion, the output pin will go
“high” and light up the LED!
This illustrates how a PIR Sensor can be used in standalone
applications.
With that, you’re now ready to upload some code and get
the PIR working.
Arduino Code
The code is very simple, and is basically just keeps track
of whether the input to pin#2 is HIGH or LOW.
Serial.begin(9600);
}
void loop(){
val = digitalRead(inputPin); // read
input value
if (pirState == LOW)
{
Serial.println("Motion
detected!"); // print on output change
pirState = HIGH;
}
}
else
{
digitalWrite(ledPin, LOW); // turn LED
OFF
if (pirState == HIGH)
{
Serial.println("Motion ended!"); //
print on output change
pirState = LOW;
}
}
}
At the end we will print a message on the serial monitor
when motion is detected.