Author: Rafael Martin Soto
Viewers: 619
Last month viewers: 142
Package: PHP Led Raspberry PI
It is also possible to use pure PHP code to control the device to perform the same operations.
Read this tutorial article to learn how to control LED lights connected to a Raspberry PI device using PHP code using simple example code.
In this article you will learn:
Introduction to Raspberry PI Hardware Control From PHP
Hardware Requirements
Knowledge Requirements
Installation
How to Access Standard GPIO Ports from PHP
How to Export a GPIO Port to Use It Physically
How to Set the Mode of Use of Port GPIO 17 AS Output
How to Turn a LED On
How to Wait 5 Second After Turning a Led On
How to Turn a LED Off
How to Unexport a GPIO Port to Stop Using It Physically
How Apply What We Learned by Gathering All the Code in a PHP Class to Control LED Lights Using a Raspberry Pi Device
How to Download the PHP Led Raspberry PI Package or Install It with PHP Composer
This photo made from pictures obtained from Wikipedia and Openclipart.
This article is based on other articles written in Spanish my Spanish PHP blog about Direct use of GPIO in PHP and Class to Light LED Lights using Raspberry PI.
Introduction to Raspberry PI Hardware Control From PHP
The objective of this article is to teach you how to turn a led on and off at very high speed using a Raspberry PI device without making calls to the shell_exec() function to run an external program.
Controlling the Raspberry PI device directly from PHP will allow direct control of the GPIO and provides direct access to GPIO ports with native PHP.
No, take it easy. This is not just another tutorial that teaches you how to turn on or off a led and that's it.
The mission of this article is to teach how to do it with PHP in an optimized way, directly accessing the GPIO ports without using shell_exec () to increase the performance of our applications, especially in the first Raspberry PI that appeared, with a limited speed of processing. Despite that limitation, it still continues to work well since the first day we made it work.
There are many ways to use LEDs with the GPIO ports on our Raspberry Pi. But here I am going to show you a technique that works with pure PHP. This is by far the one approach that achieves the fastest response time for accessing the GPIO ports.
What you will find here can be applied to any type of GPIO based project. In this example, we will focus on this typical case of turning 1 led on and off.
When you see the magic and the brightness of the LED, you are captivated. I guess that's why almost all the examples teach the same thing, that is, turn an LED on and off. It all comes down to: Brightness and Magic!!!!
I would like to add before entering fully that, as we all know, PHP is not one of the fastest languages that exist, but it is a very extensible language used in many Web servers.
The objective is to take advantage of this PHP characteristic to optimize its use in these environments. So the result that you will see in the end will not cause any envy when it comes with the speed that can be achieved using other languages, such as Python. Lets not enter into discussions about programming languages.
Hardware Requirements
Raspberry pi (any model with access to the GPIO is sufficient. I have tested it with the Raspberry Pi Model B + and it works perfectly).
SD card for the operating system.
Power supply.
Test plate.
Wiring.
1 led.
1 resistance.
HDMI cable, monitor and keyboard (for installation).
Knowledge Requirements
Basic installation of Raspbian operating system with PHP.
Connection and use of LEDs and resistors.
I will not stop to explain the basic installation. We will assume that you have the necessary basic knowledge.
Logically, under no circumstances will any responsibility for the use or damage of the hardware with your Raspberry PI device be attributed to anyone.
So you just have to be careful with what you do. All responsibility is yours. Here we will only focus on explaining how to quickly access the GPIO ports with this technique in pure PHP.
Installation
You will have to have your Raspberry PI device already prepared and running with:Raspbian (lite, for example)
PHP
SSH (Optional. I always work like this because it is very practical)
Just remember that you must activate the hardware access of the GPIOs in the raspi-config utility to be able to use them.
How to Access Standard GPIO Ports from PHP
When we use a Web server with PHP, so that at some point it accesses the GPIO ports, as common uses of turning LEDs on or off, the most normal thing is to use an external program that can be called using the PHP shell_exec().
An example:
$setmode17 = shell_exec("/usr/local/bin/gpio -g mode 17 out");
$gpio_on = shell_exec("/usr/local/bin/gpio -g write 17 1");
This would be the easiest thing to do.
The Linux operating system treats all hardware devices as if they were files, writing and reading from them.
So ... why not treat the GPIO ports the same way ??? PHP incorporates native file access libraries.
We might think that we can use this to directly access the hardware by treating each GPIO port as if it were a file.
Well yes. You can access the GPIO ports treating them as if they were files, reading and writing to them the states of active / inactive, on / off, 1/0. Easy right?
In this sense, if we can access them directly by reading or writing the on / off states (1 or 0) as if they were files, we no longer have to use the shell_exec () calls to the operating system to be able to access them through the execution of external software, saving us all these intermediate execution times.
Now we know that we can directly access the GPIO ports and how to do it in an easy, fast and also not complicated way, since it is natural to the system, so ... let's continue reading.
For any project that accesses the GPIO ports, it is necessary to do one step at the beginning and another at the end, which is the export of the ports and the UNExport.
From the export we can now configure each port to be used as input / output, and from here, the read / write operations can be used on each GPIO port.
Each of these operations separately consume processor time at the time that the PHP system must make shell calls, so the resources that these individual processes consume is transformed into process time for us, where the system is using its memory resources, processes, threads, system, etc... in creating these calls.
Then there is the loading and execution of the software, carrying out the process of turning on / off the LED itself, and later releasing the resources used again, instead of performing and focusing solely and exclusively on the task that really interests us (in this case turning on or off an LED).
The reason for having to prepare each operating system call with shell_exec () is what takes up that crucial time at times.
From the theory to the practice. Let's look directly at the code, and as Jack the Ripper said: let's go by parts.
How to Export a GPIO Port to Use It Physically
First of all it is necessary to carry out an 'export' of the GPIO port to be able to use it physically, so we will carry out an EXPORT. In our case we will use the GPIO port 17:
$fp = fopen('/sys/class/gpio/export', 'w');
fwrite($fp, '17');
fclose($fp);
How to Set the Mode of Use of Port GPIO 17 AS Output
$fp = fopen('/sys/class/gpio/gpio17/direction', 'w'); fwrite($fp, 'out'); fclose($fp);
How to Turn a LED On
Now we will tell the port to activate to turn on the LED, sending a pulse '1' to port 17:$fp = fopen('/sys/class/gpio/gpio17/ value', 'w');
fwrite($fp, '1');
fclose($fp);
How to Wait 5 Second After Turning a Led On
sleep(5);
How to Turn a LED Off
Now we only have to tell GPIO port 17 to turn off the led, so we send a pulse '0' to port 17:
$fp = fopen('/sys/class/gpio/gpio17/value', 'w'); fwrite($fp, '0'); fclose($fp);
How to Unexport a GPIO Port to Stop Using It Physically
And finally, what we will do is perform a UNEXPORT of the GPIO port 17 to release it:
$fp = fopen('/sys/class/gpio/unexport', 'w');This would be the final code so that you can test it:
fwrite($fp, '17');
fclose($fp);
<?php // EXPORT $fp = fopen('/sys/class/gpio/export', 'w'); fwrite($fp, '17'); fclose($fp); // SET GPIO17 => OUT $fp = fopen('/sys/class/gpio/gpio17/direction', 'w'); fwrite($fp, 'out'); fclose($fp); // TURN LED ON $fp = fopen('/sys/class/gpio/gpio17/value', 'w'); fwrite($fp, '1'); fclose($fp); // WAIT 5 SECONDS sleep(5); // TURN LED OFF $fp = fopen('/sys/class/gpio/gpio17/value', 'w'); fclose($fp); // UNEXPORT $fp = fopen('/sys/class/gpio/unexport', 'w'); fwrite($fp, '17'); fclose($fp); ?>
And that's it. This would be our direct access code to the super mega ultra extra fast GPIO with pure PHP.
In the end, just to turn on an LED, wait 5 seconds and then turn it off? And why do we need so much speed to do this? Well, it's not really important here. This is an example of use of the possibilities to control a Raspberry PI device. I will look to prepare a Benchmark so that you can see the differences.
You will see that the code is very simple, but everything and thus could be optimized. If you have noticed, both to turn on the LED and to turn it off, we have opened the led file, written the value and closed it.
It would not be necessary to open and close it every time we want to write a value. It would be enough to open it at the beginning of our application, turn it on and off as many times as we need and close it at the end. The optimized code would look like this:
<?php
// EXPORT
$fp = fopen ('/sys/class/gpio/export', 'w');
fwrite($fp, '17');
fclose($fp);
// SET GPIO17 => OUT
$fp = fopen('/sys/class/gpio/gpio17/direction', 'w');
fwrite($fp, 'out');
fclose($fp);
// OPEN FILE HANDLE FOR WRITE LED
$fpWriteLed17 = fopen('/sys/class/gpio/gpio17/value', 'w');
// TURN LED ON
fwrite($fpWriteLed17, '1');
// WAIT 5 SECONDS
sleep(5);
// TURN LED OFF
fwrite($fpWriteLed17, '0');
// CLOSE FILE HANDLE FOR WRITE LED
fclose($fpWriteLed17);
// UNEXPORT
$fp = fopen ('/sys/class/gpio/unexport', 'w');
fwrite($fp, '17');
fclose($fp);
?>
Now we know how we can to work directly with LEDs, then, the next work is to explain how to create an object-oriented class in PHP to be able to access the GPIO ports, specialized in LEDs and in a more organized way.
We can also optimized the use of the calls of this same class in when to open and close files as we have learned.
How Apply What We Learned by Gathering All the Code in a PHP Class to Control LED Lights Using a Raspberry Pi Device?
To use the class you only have to include it:
require_once ('led.class.php');
We must export the GPIO port before we can it.
The class is now ready to export automatically with one LED individually or with several.
If several LEDs are used, the system can be used to open a single export file and an unexport file, common for all LEDs. This means that we only have to open it once for all LEDs at the same time instead of open and close individually for each LED.
In all cases, when the LED class is created, it will inform the corresponding GPIO port, after performing the export, that this port number will be outputted, automatically without having to worry about this step at all.
In case of using a single LED (or if you do not mind opening and closing each time we create a new led class), you only have to pass the GPIO port number, since when creating the class the Export will be carried out internally. In this example we will use an LED linked to GPIO port 17:
$Led17 = new Led('17'); // Use the led as we need, such as: // Turn on the led of GPIO port 17, wait a second, turn it off $Led17->On(); sleep(1); $Led17->Off(); $Led17->unexport();Remember that you have to perform the Unexport after using the led. In this case the class will open the unexport file, perform the unexport, and then close the file automatically.
We can also use it individually for several LEDs. The export and unexport will be carried out individually for each of them. For example:
// We create the Led class and assign it to the variables we use, passing the GPIO port number as a parameter: $Led17 = new Led('17'); $Led18 = new Led('18'); // Use the LEDs as we need, such as: // Turn on the led of the GPIO port 17, wait a second, turn it off, turn on the led of the GPIO port 18, wait a second, turn it off $Led17->On(); sleep(1); $Led17->Off(); sleep(1); $Led18->On(); sleep(1); $Led18->Off();
Remember at the end of our code to perform the Unexport. In this case, the class will open the unexport file, perform the unexport, and then automatically close the file for each of the LEDs.
$Led17->unexport(); $Led18->unexport();
In case you want to take advantage of the optimization of the use of resources for several LEDs, using a common export and unexport 'file handle' for all the LEDs, you must use the method as follows:
// We open the export and unexport files and assign them to the variables $fpUnexport and $fpExport respectively $fpUnexport = fopen('/sys/class/gpio/unexport', 'w'); $fpExport = fopen('/sys/class/gpio/export', 'w'); // We create the Led class and assign it to the variables we use, passing as parameters the GPIO port number and the previous variables $fpExport and $fpUnexport $Led17 = new Led('17', $fpUnexport, $fpExport); $Led18 = new Led('18', $fpUnexport, $fpExport); // After creating the variables of the LED class, we no longer need the pointer to the file $fpExport. We close it and free memory fclose($fpExport); unset($fpExport); // Turn on the led of the GPIO port 17, wait a second, turn it off, turn on the led of the GPIO port 18, wait a second, turn it off $Led17->On(); sleep(1); $Led17->Off(); sleep(1); $Led18->On(); sleep(1); $Led18->Off();
Remember at the end of our code to perform the Unexport and close the $fpExport and $fpUnexport files.
When using the file pointer of $fpUnexport and $fpExport, when an unexport is performed, the class will NOT close the file because it affects the other LED variables, so we must close it at the time of terminating the program.
When using the file pointer of $fpUnexport and $fpExport, when an unexport is performed, the class will NOT close the file because it affects the other LED variables, so we must close it at the time of terminating the program.
$Led18->unexport(); fclose($fpUnexport); $Led17->unexport(); $Led18->unexport(); fclose($fpUnexport); $Led17->unexport();
Well nothing, you already have a quick access class in PHP to turn LEDs on and off. It is very simple, optimized and effective at the same time.
How to Download the PHP Led Raspberry PI Package or Install It with PHP Composer
The PHP Print Labels to PDF package can be downloaded from download page or be installed using the PHP Composer tool following instructions in the Composer install instructions page. You can also access it in GitHub.
You need to be a registered user or login to post a comment
Login Immediately with your account on:
Comments:
1. permissions - Joan Barns (2021-10-13 18:41)
I have to refresh the page once to get permissions working... - 3 replies
Read the whole comment and replies