PHP code example of tgeindre / php-gpio

1. Go to this page and download the library: Download tgeindre/php-gpio library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

tgeindre / php-gpio example snippets



namespace myproject;

$pi = new PhpGpio\Utils\Pi;
$pi->getAvailablePins(); // int array


namespace MyProject;

use PhpGpio\GpioInterface;
use PhpGpio\Gpio;

// Both pins are available on all raspi versions
define('PIN_IN', 4);
define('PIN_OUT', 7);

$gpio = new Gpio([PIN_IN, PIN_OUT]);

// First, setup pins with correct directions
$gpio
     ->setup(PIN_IN, GpioInterface::DIRECTION_IN) // Makes it readable
     ->setup(PIN_OUT, GpioInterface::DIRECTION_OUT) // Writeable
;

// read PIN_IN value and display it
$value = $gpio->read(PIN_IN);
var_dump($value); // string

// write 1 on PIN_OUT
$gpio->write(PIN_OUT, GpioInterface::IO_VALUE_ON);
sleep(1);

// After 1 second, write 0 on PIN_OUT
$gpio->write(PIN_OUT, GpioInterface::IO_VALUE_OFF);

// Then free all pins
// (use the unexport() method to free pins one by one)
$gpio->unexportAll();

namespace MyProject;

use PhpGpio\Gpio;
use PhpGpio\Sensor\Mcp\Mcp3008;

// Defining pins mapping according to your setup
$pinsMapping = [
    'MISO' => 17,
    'MOSI' => 8,
    'CLK' => 23,
    'CS' => 24,
];

// Setup a Gpio class
$gpio = new Gpio(array_values($pins));

// Then we can instanciate the MCP class
$mcp = new Mcp3008(
    $gpio
    $mapping['CLK'],
    $mapping['MOSI'],
    $mapping['MISO'],
    $mapping['CS']
);

// Now let's read some data on the first channel
while (true) {
    echo $mcp->read(['channel' => 0]), "\n";
    // every second
    sleep(1);
}