source:Interfaces/SPI/SPI_Interfaces.png

SPI

The SPI Interface provides a "Serial Peripheral Interface" Master.

This interface can be used for communication with SPI slave devices, such as FLASH memory, LCD screens and other modules or integrated circuits.

Hello World!

// Example code for reading the "WHOAMI" register of an LIS302 SPI accelerometer.

#include "mbed.h"

SPI spi(p5, p6, p7); // mosi, miso, sclk
DigitalOut cs(p8);

Serial pc(USBTX, USBRX); // tx, rx

int main() {
    // Setup the spi for 8 bit data, high steady state clock,
    // second edge capture, with a 1MHz clock rate
    spi.format(8,1,1);
    spi.frequency(1000000);

    // Select the device by seting chip select low
    cs = 0;

    // Send 0x8f, the command to read the WHOAMI register
    spi.write(0x8F);

    // Send a dummy byte to receive the contents of the WHOAMI register
    int whoami = spi.write(0x00);
    pc.printf("WHOAMI register = 0x%X\n", whoami);

    // Deselect the device
    cs = 1;
}

API

SPIA SPI Master, used for communicating with SPI slave devices
Functions
SPICreate a SPI master connected to the specified pins
formatConfigure the data transmission format
frequencySet the spi bus clock frequency
writeWrite to the SPI Slave and return the response
class SPI : public Base
A SPI Master, used for communicating with SPI slave devices
SPI(PinName mosi,  
PinName miso,  
PinName sclk,  
const char *name =  NULL)
Create a SPI master connected to the specified pins
void format(int bits,  
int mode =  0)
Configure the data transmission format
void frequency(int hz =  1000000)
Set the spi bus clock frequency
int write(int value)
Write to the SPI Slave and return the response
class DigitalOut : public Base
A digital output, used for setting the state of a pin

Detials

The SPI Interface can be used on mbed pins p5/p6/p7 and p11/p12/p13

The SPI Interface can be used to write data words out of the SPI port, returning the data received back from the SPI slave. The SPI clock frequency and format can also be configured.

The SPI master generates a clock to synchronously drive a serial bit stream slave. The slave returns a bit stream, also synchronous to the clock.

Reference