PHP code example of php-io-extensions / fd

1. Go to this page and download the library: Download php-io-extensions/fd 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 / fd example snippets


// O_WRONLY | O_NONBLOCK on Linux
$fd = Fd\FD::open('/dev/ttyUSB0', 1 | 2048);

$fd = Fd\FD::open(string $device_path, int $flags): int

// Open an I2C device for reading and writing (O_RDWR = 2)
$fd = Fd\FD::open('/dev/i2c-1', 2);

if ($fd < 0) {
    throw new RuntimeException("Failed to open device");
}

$result = Fd\FD::close(int $fd): int

Fd\FD::close($fd);

$result = Fd\FD::addFlags(int $fd, int $flags): int

// Set O_NONBLOCK on an open descriptor (Linux: 2048, macOS: 4)
Fd\FD::addFlags($fd, 2048);

// Combine flags: O_NONBLOCK | O_APPEND on Linux
Fd\FD::addFlags($fd, 2048 | 1024);

$data = Fd\FD::read(int $fd, int $bytes_to_read): string

// Read 2 bytes from a UART device
$bytes = Fd\FD::read($fd, 2);

$written = Fd\FD::write(int $fd, string $data, int $bytes_to_write): int

// Send a command byte over SPI
Fd\FD::write($fd, "\x3A", 1);

// O_RDWR = 2
$fd = Fd\FD::open('/dev/i2c-1', 2);

if ($fd < 0) {
    throw new RuntimeException('Could not open I2C device');
}

// Write a register address
Fd\FD::write($fd, "\x00", 1);

// Read 2 bytes back
$data = Fd\FD::read($fd, 2);

Fd\FD::close($fd);
shell
php -m | grep fd
php --ri fd