I wanted to make a LED light up using PHP on a Raspberry Pi. Most of the examples I’ve seen are for Python, so I wanted to see if was possible or not.
It is actually pretty easy to do, so I thought I’d share my work.
The first thing to do is to wire up the LED to the Raspberry Pi. I used a breadboard so there is no soldering required.
Connect the LED to GPIO pin 18, along with a 330ohm resistor, to GND. We need the resistor to limit the current through the LED otherwise it could burn out.
That’s the LED attached to Raspberry Pi, now we need to control it with PHP code.
PHP LED Control Code
Before we can write any PHP, we need to enable the gpio module on the Raspberry Pi.
sudo modprobe w1-gpio
We need a third party PHP library to be able to talk to the GPIO pins. I’m using php-gpio.
We need to install this with Composer before we can use it.
get http://getcomposer.org/composer.phar php composer.phar require ronanguilloux/php-gpio
We can now start our PHP code by using the autoloader to bring in the GPIO library.
require 'vendor/autoload.php'; use PhpGpio\Gpio; $gpio = new GPIO();
Now to control the LED we need to make sure GPIO pin 18 is set to “out”.
$gpio->setup(18, 'out');
To turn the LED on we write the value “1” to pin 18.
$gpio->output(18, 1);
To turn the LED off we write the value “0” to pin 18.
$gpio->output(18, 0);
Finally, we need to make sure we clean up after ourselves.
$gpio->unexportAll();
The Final Code
Bringing this all together, we can write a simple PHP script to turn the LED on, wait 1 second, and turn it off again.
<?php require 'vendor/autoload.php'; use PhpGpio\Gpio; $gpio = new GPIO(); $gpio->setup(18, 'out'); echo "LED on\n"; $gpio->output(18, 1); sleep(1); echo "LED off\n"; $gpio->output(18, 0); $gpio->unexportAll();
The final code needs to be run as root to be able to access gpio.