SPI

Mbed OS 2 and Mbed OS 5

This is the handbook for Mbed OS 2. If you’re working with Mbed OS 5, please see the Mbed OS 5 documentation. For the latest SPI API, please see 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!

Import program

00001 #include "mbed.h"
00002  
00003 SPI spi(p5, p6, p7); // mosi, miso, sclk
00004 DigitalOut cs(p8);
00005  
00006 int main() {
00007     // Chip must be deselected
00008     cs = 1;
00009 
00010     // Setup the spi for 8 bit data, high steady state clock,
00011     // second edge capture, with a 1MHz clock rate
00012     spi.format(8,3);
00013     spi.frequency(1000000);
00014  
00015     // Select the device by seting chip select low
00016     cs = 0;
00017  
00018     // Send 0x8f, the command to read the WHOAMI register
00019     spi.write(0x8F);
00020  
00021     // Send a dummy byte to receive the contents of the WHOAMI register
00022     int whoami = spi.write(0x00);
00023     printf("WHOAMI register = 0x%X\n", whoami);
00024  
00025     // Deselect the device
00026     cs = 1;
00027 }

API

Import librarymbed

No documentation found.

Interface

/media/uploads/chris/pinout-thumbnails.jpg
See the Pinout page for more details

The default settings of the SPI interface are 1MHz, 8-bit, Mode 0

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 format is set to data word length 8 to 16 bits, and the mode as per the table below:

ModePolarityPhase
000
101
210
311

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