Using a motion sensor on a Raspberry Pi with PHP

HC-SR501 motion sensor attached to a Raspberry Pi

Adding a motion sensor to a Raspberry Pi is easy. In this article I’ll show you how to use it with PHP.

The HC-SR501 is a pyroelectric infrared PIR motion sensor module, that connects to the Raspberry Pi using just 3 wires.

Connect GND to GND on the Pi, VCC to +5V on the Pi, and OUT to GPIO 17 on the Pi. That’s all that’s needed.

Added a HC-SR501 motion detector to a Raspberry Pi

To use the sensor with PHP we use the PHPi library. This library supports event driven bindings for the Raspberry Pi GPIO. We install this using Composer.

composer require calcinai/phpi

To use the PHPi library we need to bring it in using the autoloader, and add some namespace shortcuts.

require 'vendor/autoload.php';

use Calcinai\PHPi\Pin;
use Calcinai\PHPi\Pin\PinFunction;

We then create a board

$board = \Calcinai\PHPi\Factory::create();

We now need to declare that we’re using GPIO pin 17 for input.

$pin = $board->getPin(17)
             ->setFunction(PinFunction::INPUT)
             ->setPull(Pin::PULL_UP);

As this is event driven programming, we need to listen to the pin to see when it changes. When the pin goes high, we know motion has been detected and we can do something. In this example, we’ll just write a message to the screen.

$pin->on('level.high', function() {
        echo "Motion detected\n";
});

Finally we start the start the loop running, so the script is listening and reacting to events.

$board->getLoop()->run();

Putting it all together

Here’s the final working PHP to detect motion using the HC-SR501

<?php

require 'vendor/autoload.php';

use Calcinai\PHPi\Pin;
use Calcinai\PHPi\Pin\PinFunction;

$board = \Calcinai\PHPi\Factory::create();

$pin = $board->getPin(17) //BCM pin number
             ->setFunction(PinFunction::INPUT)
             ->setPull(Pin::PULL_UP);

$pin->on('level.high', function() {
        echo "Motion detected\n";
});

$board->getLoop()->run();