This article was revised on 2021/11/18 by Karl Söderby.
Controller/peripheral is formerly known as master/slave. Arduino no longer supports the use of this terminology. See the table below to understand the new terminology:
Master/Slave (OLD) | Controller/Peripheral (NEW) |
---|---|
Master In Slave Out (MISO) | Controller In, Peripheral Out (CIPO) |
Master Out Slave In (MOSI) | Controller Out Peripheral In (COPI) |
Slave Select pin (SS) | Chip Select Pin (CS) |
The SPI Library is included in every Arduino core/platform, so you do not need to install it externally. You can read more about SPI functions in the links below:
With an SPI connection there is always one Controller device (usually a microcontroller) which controls the peripheral devices. Typically there are three lines common to all the devices:
To write code for a new SPI device you need to note a few things:
Generally speaking, there are four modes of transmission. These modes control whether data is shifted in and out on the rising or falling edge of the data clock signal (called the clock phase), and whether the clock is idle when high or low (called the clock polarity). The four modes combine polarity and phase according to this table:
Mode | Clock Polarity (CPOL) | Clock Phase (CPHA) | Output Edge | Data Capture |
---|---|---|---|---|
SPI_MODE0 | 0 | 0 | Falling | Rising |
SPI_MODE1 | 0 | 1 | Rising | Falling |
SPI_MODE2 | 1 | 0 | Rising | Falling |
SPI_MODE3 | 1 | 1 | Falling | Rising |
Once you have your SPI parameters, use
SPI.beginTransaction()
to begin using the SPI port. The SPI port will be configured with your all of your settings. The simplest and most efficient way to use SPISettings is directly inside SPI.beginTransaction()
. For example:1SPI.beginTransaction(SPISettings(14000000, MSBFIRST, SPI_MODE0));
If other libraries use SPI from interrupts, they will be prevented from accessing SPI until you call
SPI.endTransaction()
. The SPI settings are applied at the begin of the transaction and SPI.endTransaction()
doesn't change SPI settings. Unless you, or some library, calls beginTransaction a second time, the setting are maintained. You should attempt to minimize the time between before you call SPI.endTransaction()
, for best compatibility if your program is used together with other libraries which use SPI.With most SPI devices, after
SPI.beginTransaction()
, you will write the Chip Select pin LOW, call SPI.transfer()
any number of times to transfer data, then write the CS pin HIGH, and finally call SPI.endTransaction()
.For more on SPI, see Wikipedia's page on SPI.