1. Go to this page and download the library: Download microscrap/spi 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 / spi example snippets
use Microscrap\Bindings\SPI\DataObjects\SPITransfer;
use Microscrap\Bindings\SPI\Enums\SPIMode;
// Open spidev0.0 at 500 kHz, mode 1 (CPHA=1, CPOL=0), 8 bits/word.
$dev = spi_open('/dev/spidev0.0', SPIMode::CPHA->value, 500_000, 8);
if ($dev === null) {
exit("Failed to open SPI device\n");
}
// Full-duplex read of register 0x07. Many SPI sensors use bit 6 of the first
// byte to flag a read; adjust to match your device's protocol.
$rx = spi_transfer(
$dev,
new SPITransfer(tx: pack('CC', 0x07 | 0x40, 0x00), len: 2),
);
if ($rx === false) {
exit("Transfer failed\n");
}
printf("REG 0x07 = 0x%02X\n", ord($rx[1]));
spi_close($dev);
use Microscrap\Bindings\SPI\DataObjects\SPITransfer;
$dev = spi_open('/dev/spidev0.0', 0, 1_000_000, 8);
$rx = spi_transfer(
$dev,
new SPITransfer(tx: "\x9F", len: 1), // JEDEC ID command
new SPITransfer(tx: str_repeat("\0", 3), len: 3), // 3 bytes manufacturer + device ID
);
if ($rx === false || strlen($rx) !== 4) {
exit("Transfer failed\n");
}
// Skip the first byte (clocked out during command phase).
printf("JEDEC ID: %s\n", strtoupper(bin2hex(substr($rx, 1))));
spi_close($dev);
final readonly class SPIDevice {
public int $fd; // open file descriptor
public string $path; // device path (/dev/spidev0.0)
public int $mode; // SPIMode bitmask the device was opened with
public int $speed; // max clock speed (Hz) configured at open time
public int $bitsPerWord; // word size configured at open time
}
final readonly class SPITransfer {
public function __construct(
public string $tx, // bytes clocked out on MOSI (padded/truncated to $len)
public int $len, // total bytes clocked in each direction
public int $speedHz = 0, // override device speed (0 = use device default)
public int $delayUsecs = 0, // microseconds to hold after this segment
public int $bitsPerWord = 0, // override device word size (0 = use device default)
public bool $csChange = false, // de-assert CS after this segment
public int $txNbits = 0, // 1 / 2 / 4 / 8 — dual/quad/octal MOSI
public int $rxNbits = 0, // 1 / 2 / 4 / 8 — dual/quad/octal MISO
public int $wordDelayUsecs = 0, // microseconds between words
) {}
}
use Microscrap\Bindings\SPI\Enums\SPIOpCode;
$ioctl = SPIOpCode::messageN(3); // request for 3 chained spi_ioc_transfer structs
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.