PHP code example of php-io-extensions / gpio
1. Go to this page and download the library: Download php-io-extensions/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/ */
php-io-extensions / gpio example snippets
use Fd\FD;
$fd = FD::open('/dev/gpiochip0', 2); // O_RDWR = 2
// ... use $fd with GPIOChip methods ...
FD::close($fd);
['name' => string, 'label' => string, 'lines' => int]
['name' => string, 'consumer' => string, 'offset' => int, 'num_attrs' => int, 'flags' => int]
[
'info' => ['name' => string, 'consumer' => string, 'offset' => int, 'num_attrs' => int, 'flags' => int],
'timestamp_ns' => int,
'event_type' => int, // 1 = REQUESTED, 2 = RELEASED, 3 = CONFIG_CHANGED
]
[
'timestamp_ns' => int,
'id' => int, // 1 = RISING_EDGE, 2 = FALLING_EDGE
'offset' => int,
'seqno' => int,
'line_seqno' => int,
]
use Fd\FD;
use Gpio\GPIOChip;
use Gpio\GPIOLine;
$fd = FD::open('/dev/gpiochip4', 2); // O_RDWR
$lineFd = GPIOChip::getLine($fd, 6, 0x08, 0, 'my-app'); // OUTPUT
if ($lineFd < 0) {
throw new RuntimeException('Failed to request line');
}
GPIOLine::setValues($lineFd, 1); // HIGH — device on
sleep(1);
GPIOLine::setValues($lineFd, 0); // LOW — device off
FD::close($lineFd);
FD::close($fd);
$fd = FD::open('/dev/gpiochip0', 2);
$lineFd = GPIOChip::getLine($fd, 27, 0x04, 0, 'my-app'); // INPUT
$state = GPIOLine::getValues($lineFd);
echo $state === 1 ? "HIGH\n" : "LOW\n";
FD::close($lineFd);
FD::close($fd);
// INPUT | EDGE_RISING | EDGE_FALLING
$fd = FD::open('/dev/gpiochip0', 2);
$lineFd = GPIOChip::getLine($fd, 27, 0x04 | 0x10 | 0x20, 64, 'my-app');
while (true) {
$event = GPIOLine::readEdgeEvents($lineFd);
if ($event !== []) {
$edge = $event['id'] === 1 ? 'RISING' : 'FALLING';
echo "{$edge} on offset {$event['offset']} at {$event['timestamp_ns']} ns\n";
}
}
$fd = FD::open('/dev/gpiochip0', 2);
$chip = GPIOChip::chipInfo($fd);
echo "Chip: {$chip['name']} — {$chip['label']} ({$chip['lines']} lines)\n";
$line = GPIOChip::lineInfo($fd, 6);
echo "Line 6: consumer={$line['consumer']} flags={$line['flags']}\n";
FD::close($fd);