Skip to content
php-baremetal REGISTRY
Publish a package

php-baremetal/ext-spi

bm-ext MIT

Baremetal\Spi\Bus + \Device and the device-driver framework. Drivers are packages registering into the spi_drivers registry; the platform side is a spi-hal package.

bus: spi

ext-spi · PHP API

Bus

Baremetal\Spi\Bus is a handle onto one SPI host and its pins. Same host, same bus: constructing it twice with the same pins is safe and cheap.

Baremetal\Spi\Bus opens a SPI master host on a clock pin and its data pins. The bus lives for the whole run: a second new Bus() on the same host with the same pins returns the same underlying bus, so libraries can each construct their own Bus object without coordinating.

Constructor

new Bus(int $sclk, int $mosi, int $miso = -1, int $data2 = -1, int $data3 = -1, int $host = 1)

Public method.

Parameters

$sclk int required

GPIO number of the clock line.

$mosi int required

GPIO number of MOSI. On a QSPI bus this is data line 0.

$miso int optional, default -1

GPIO number of MISO, or -1 for a write-only bus. On a QSPI bus this is data line 1.

$data2 int optional, default -1

QSPI data line 2. The bus is four-line only when both $data2 and $data3 are given.

$data3 int optional, default -1

QSPI data line 3.

$host int optional, default 1

The platform's SPI host number, the key of the bus, from 1 to 255 (anything else throws \ValueError). On ESP32 chips 1 is SPI2_HOST and 2 is SPI3_HOST.

Throws \Exception cannot open SPI host N: ... when:

  • the host is already open with other pins, or one of the pins belongs to a bus open on another host (the host or a pin is already used by an SPI bus open with other pins);
  • both bus slots are in use (ESP_ERR_NO_MEM);
  • the HAL cannot initialise the host, for example because the firmware already uses it (on ESP32, spi_bus_initialize fails with ESP_ERR_INVALID_STATE).

On ESP32 the host is set up with DMA (channel picked automatically) and a maximum transfer of 32768 bytes.

device()

Bus::device(int $cs, int $hz = 1000000, int $mode = 0): Device

Public method. Returns Device.

Attaches the chip whose chip select is GPIO $cs, clocked at $hz in SPI mode $mode (0 to 3), and returns a raw Device. Same as new Device($bus, $cs, $hz, $mode).

Devices are kept per bus and CS pin: asking again for a CS returns the existing device (the new $hz and $mode are ignored). If a driver class already holds that CS, it throws cannot add SPI device cs=N: chip select already used by another driver on this bus.

php two chips on one bus
<?php
use Baremetal\Spi\Bus;

$bus   = new Bus(sclk: 12, mosi: 11, miso: 13);
$flash = $bus->device(cs: 10, hz: 10_000_000);        // mode 0
$adc   = $bus->device(cs: 9, hz: 1_000_000, mode: 1);

The bus has no other methods. There is no close(): a bus stays open until the board restarts.

Related