Passive infrared (PIR) motion sensors

A passive infrared (PIR) motion sensor can detect changes in infrared radiation, most often in order to detect the motion or presence of people or animals.

The sensor can be thought of as a two-pixel infrared camera. It has two internal infrared sensors and circuitry to detect changes between them. The internal sensors are covered by a Fresnel lens that determines the PIR device's field of view.

The following relates specifically to the HC-SR501 model, but it should also apply to similar PIR motion sensors for hobbyists.

The PIR device normally sits in a LOW state. When motion is being detected, the device will output a HIGH signal. After motion has ceased, it will change back to LOW.

To handle this in code, we use a variable to store the previous reading (defaulting to LOW), and compare this to the current reading. If the two are different, then motion has either just started or ended.


// Arduino pin connected to PIR's OUT pin
const int pirPin = 4;

// Default PIR state is LOW (no motion)
const int pirState = LOW;

void setup()
{
	pinMode(pirPin, INPUT);
}

void loop()
{
	int newPirState = digitalRead(pirPin);

	if (newPirState == HIGH)
	{
		if (pirState == LOW)
		{
			// Record new state
			pirState = HIGH;

			// Handle motion detected...
		}

		// Handle continued motion...
	}
	else
	{
		if (pirState == HIGH)
		{
			// Record new state
			pirState = LOW;

			// Handle motion ended...
		}

		// Handle continued non-motion...
	}
}