piphp/gpio

A library for accessing the GPIO pins on a Raspberry Pi

Maintainers

Details

github.com/PiPHP/GPIO

Source

Issues

Installs: 5 319

Dependents: 2

Suggesters: 1

Security: 0

Stars: 431

Watchers: 21

Forks: 42

Open Issues: 11

0.4.0 2020-08-24 13:50 UTC

This package is auto-updated.

Last update: 2024-11-25 23:53:03 UTC


README

License Total Downloads

A library for low level access to the GPIO pins on a Raspberry Pi. These pins can be used to control outputs (LEDs, motors, valves, pumps) or read inputs (sensors).

By AndrewCarterUK (Twitter)

Installing

Using composer:

composer require piphp/gpio

Or:

php composer.phar require piphp/gpio

Examples

Setting Output Pins

use PiPHP\GPIO\GPIO;
use PiPHP\GPIO\Pin\PinInterface;

// Create a GPIO object
$gpio = new GPIO();

// Retrieve pin 18 and configure it as an output pin
$pin = $gpio->getOutputPin(18);

// Set the value of the pin high (turn it on)
$pin->setValue(PinInterface::VALUE_HIGH);

Input Pin Interrupts

use PiPHP\GPIO\GPIO;
use PiPHP\GPIO\Pin\InputPinInterface;

// Create a GPIO object
$gpio = new GPIO();

// Retrieve pin 18 and configure it as an input pin
$pin = $gpio->getInputPin(18);

// Configure interrupts for both rising and falling edges
$pin->setEdge(InputPinInterface::EDGE_BOTH);

// Create an interrupt watcher
$interruptWatcher = $gpio->createWatcher();

// Register a callback to be triggered on pin interrupts
$interruptWatcher->register($pin, function (InputPinInterface $pin, $value) {
    echo 'Pin ' . $pin->getNumber() . ' changed to: ' . $value . PHP_EOL;

    // Returning false will make the watcher return false immediately
    return true;
});

// Watch for interrupts, timeout after 5000ms (5 seconds)
while ($interruptWatcher->watch(5000));

Further Reading

SitePoint published a tutorial about powering Raspberry Pi projects with PHP which used this library and shows a push button example with a wiring diagram.

More Resources

PiPHP maintains a resource directory for PHP programming on the Raspberry Pi.