PHP code example of microscrap / gpio
1. Go to this page and download the library: Download microscrap/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/ */
microscrap / gpio example snippets
use Microscrap\Bindings\GPIO\Enums\LineDirection;
use Microscrap\Bindings\GPIO\Enums\LineEdge;
use Microscrap\Bindings\GPIO\Enums\LineValue;
$chip = gpiod_chip_open('/dev/gpiochip0');
$led_settings = gpiod_line_settings_new();
gpiod_line_settings_set_direction($led_settings, LineDirection::OUTPUT);
gpiod_line_settings_set_output_value($led_settings, LineValue::INACTIVE);
$btn_settings = gpiod_line_settings_new();
gpiod_line_settings_set_direction($btn_settings, LineDirection::INPUT);
gpiod_line_settings_set_edge_detection($btn_settings, LineEdge::RISING);
$line_config = gpiod_line_config_new();
gpiod_line_config_add_line_settings($line_config, [17], $led_settings);
gpiod_line_config_add_line_settings($line_config, [27], $btn_settings);
$req_config = gpiod_request_config_new();
gpiod_request_config_set_consumer($req_config, 'blink-example');
$request = gpiod_chip_request_lines($chip, $req_config, $line_config);
// Blink 5 times
for ($i = 0; $i < 5; $i++) {
gpiod_line_request_set_value($request, 17, LineValue::ACTIVE);
usleep(500_000);
gpiod_line_request_set_value($request, 17, LineValue::INACTIVE);
usleep(500_000);
}
gpiod_line_request_release($request);
gpiod_chip_close($chip);
$chip = gpiod_chip_open('/dev/gpiochip0');
if ($chip === null) {
throw new RuntimeException('Failed to open GPIO chip');
}
$info = gpiod_chip_get_info($chip);
echo $info->name . ' — ' . $info->num_lines . " lines\n";
$line = gpiod_chip_get_line_info($chip, 17);
echo $line->name . ' used=' . ($line->used ? 'yes' : 'no') . "\n";
$ready = gpiod_chip_wait_info_event($chip, 1_000_000_000); // 1 s
if ($ready === 1) {
$event = gpiod_chip_read_info_event($chip);
}
$offset = gpiod_chip_get_line_offset_from_name($chip, 'GPIO17');
$request = gpiod_chip_request_lines($chip, $req_config, $line_config);
if ($request === null) {
throw new RuntimeException('Failed to request lines');
}
$line_config = gpiod_line_config_new();
gpiod_line_config_add_line_settings($line_config, [4, 17, 27], $settings);
$v = gpiod_line_request_get_value($request, 27);
echo $v === LineValue::ACTIVE ? "HIGH\n" : "LOW\n";
gpiod_line_request_set_value($request, 17, LineValue::ACTIVE);
$buffer = gpiod_edge_event_buffer_new(16);
$ready = gpiod_line_request_wait_edge_events($request, -1); // block
if ($ready === 1) {
$n = gpiod_line_request_read_edge_events($request, $buffer, 16);
for ($i = 0; $i < $n; $i++) {
$event = gpiod_edge_event_buffer_get_event($buffer, $i);
printf("offset=%d type=%s ts=%d ns\n",
$event->line_offset,
$event->event_type->name,
$event->timestamp_ns,
);
}
}