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|
Once you have your SPI parameters, use
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
. 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
. The SPI settings are applied at the begin of the transaction and
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
, for best compatibility if your program is used together with other libraries which use SPI.
With most SPI devices, after
, you will write the Chip Select pin LOW, call
any number of times to transfer data, then write the CS pin HIGH, and finally call
For more on SPI, see Wikipedia's page on SPI.