Introduction to SPI#

Arduino SPI Library Docs#

Arduino & Serial Peripheral Interface (SPI) | Arduino Documentation

Arduino UNO SPI Hardware#

arduino-uno-SPI-pins

The Arduino Uno has built-in hardware support for SPI communication.

  • MOSI − 11 or ICSP-4

  • MISO − 12 or ICSP-1

  • SCK − 13 or ICSP-3

  • SS − 10

Built-in SPI library#

The important functions of this library are given below −

  • SPI.begin() → Initialize SPI

  • SPI.transfer() → Transfer data to peripheral

  • SPI.beginTransaction() → Begin using SPI port

  • SPI.endTransaction() → End the current transactions (if other libraries are using SPI from interrupts, they will be prevented from accessing SPI until you call this function)

  • SPI.beginTransaction(SPISettings(14000000, MSBFIRST, SPI_MODE0)) → Change SPI settings while beginning transaction. These settings will remain in place till another call to beginTransaction along with SPISettings alters these settings.

First SPI Tutorial#

How to Use SPI Communication on the Arduino - Circuit Basics

这个例子以数字可调电位器(MCP4131 Digital Potentiometer)为例 [1] 说明了 SPI Hardware SPI Library 的用法,例子演示了 SPI.transfer() 函数用于读写的用法。难度小,概念清楚,重点明确,在了解了 SPI 的基本原理后,就可以学习这个例子。

不过这个例子没有讲 SPI 库中的其它函数的用法。

SPI.transfer() 说明

  • 片选(CS/SS)是不包含在 transfer() 之中的;You must specify each pin you wish to use as CS for the SPI devices.

  • transfer() 仅仅只完成在时钟的驱动下,将值串行通过 MOSI 口发出,和 ShiftOut() 函数的功能相同,但是不用自己定义和实现移位方向,CLK 引脚,模式等;

  • transfer() 是由硬件完成的,所以比软件的 ShiftOut() 模拟实现更高效,节省 CPU 时间

  • transfer() 函数在发送的同时完成接收

To send commands to the MCP4131, we need to use the SPI.transfer(*val*) function. The val parameter is the data that we want to send over the SPI. This function also returns the data received from the MCP4131.

#include <SPI.h>
void setup() {
  pinMode(10, OUTPUT); // set the SS pin as an output
  SPI.begin();         // initialize the SPI library
}

void loop() {
  byte value = 123;
  digitalWrite(10, LOW);            // set the SS pin to LOW
  SPI.transfer(value);      // send a new wiper value
  digitalWrite(10, HIGH);           // set the SS pin HIGH
}

Extented SPI Library#

只有 Arduino Due 才具有的功能,涉及到 SPI 硬件的寄存k器配置方法

Extended SPI Library Usage with the Arduino Due | Arduino Documentation

I2C Tutorials#

Arduino I2C Tutorial: I2C Communication Between Arduino Boards

TCA9548A I2C Multiplexer: ESP32, ESP8266, Arduino | Random Nerd Tutorials