Example of Using SPI


Write Data to a Slave

The following code is a common example that an SPI master writes data to a slave.

example of writing data

<?php
$wbuf = 0xA2;                       // Data to be sent
$rbuf = "";

$pid = pid_open("/mmap/spi0");      // open SPI0
pid_ioctl($pid, "set mode 3");      // set SPI mode to 3
pid_ioctl($pid, "set lsb 0");       // set bit transmission order: MSB first
pid_write($pid, $wbuf, 1);          // write 1 byte to buffer: 0xA2
pid_ioctl($pid, "req start");       // request to write data
while(pid_ioctl($pid, "get txlen")) // check the size of transmitted data
    ;
pid_read($pid, $rbuf, 1);           // read 1 byte
pid_close($pid);
?>

The reason of reading 1 byte in the bottom of the above example is because reading and writing data are simultaneously implemented at all times in SPI communication.

Read Data from a Slave

The following code is a common example that an SPI master reads data from a slave.

example of reading data

<?php
$wbuf = 0x00;                       // Data to be sent
$rbuf = "";

$pid = pid_open("/mmap/spi0");      // open SPI0
pid_ioctl($pid, "set mode 3");      // set SPI mode to 3
pid_ioctl($pid, "set lsb 0");       // set bit transmission order: MSB first
pid_write($pid, $wbuf, 1);          // write 1 byte to buffer: 0x00
pid_ioctl($pid, "req start");       // request to write data
while(pid_ioctl($pid, "get txlen")) // check the size of transmitted data
    ;
pid_read($pid, $rbuf, 1);           // read 1 byte
pid_close($pid);
?>