SPITransaction Method

In this tutorial you will learn how to use the SPI transaction methods.

SPI transaction example

In this tutorial you will learn how to use the SPI transaction methods. For an explanation of SPI see the SPI EEPROM tutorial.

A common problem used to be that different SPI devices needed different, incompatible settings. Your sketch had to take care of saving and restoring the SPI settings before communicating with each SPI device. If any SPI device was accessed from an interrupt, this could result in data corruption if another SPI device was communicating at the time.

With the new SPI library, configure each SPI device once as an SPISettings object. Also, if that device will be called from an interrupt, say so with SPI.usingInterrupt(interruptNumber). To communicate with a specific SPI device, use SPI.beginTransaction which automatically uses the settings you declared for that device. In addition, it will disable any interrupts that use SPI for the duration of the transaction. Once you are finished, use SPI.endTransaction() which re-enables any SPI-using interrupts.

Code

1#include <SPI.h>
2
3// using two incompatible SPI devices, A and B. Incompatible means that they need different SPI_MODE
4
5const int slaveAPin = 20;
6
7const int slaveBPin = 21;
8
9// set up the speed, data order and data mode
10
11SPISettings settingsA(2000000, MSBFIRST, SPI_MODE1);
12
13SPISettings settingsB(16000000, LSBFIRST, SPI_MODE3);
14
15void setup() {
16
17 // set the Slave Select Pins as outputs:
18
19 pinMode (slaveAPin, OUTPUT);
20
21 pinMode (slaveBPin, OUTPUT);
22
23 // initialize SPI:
24
25 SPI.begin();
26}
27
28uint8_t stat, val1, val2, result;
29
30void loop() {
31
32 // read three bytes from device A
33
34 SPI.beginTransaction(settingsA);
35
36 digitalWrite (slaveAPin, LOW);
37
38 // reading only, so data sent does not matter
39
40 stat = SPI.transfer(0);
41
42 val1 = SPI.transfer(0);
43
44 val2 = SPI.transfer(0);
45
46 digitalWrite (slaveAPin, HIGH);
47
48 SPI.endTransaction();
49
50 // if stat is 1 or 2, send val1 or val2 else zero
51
52 if (stat == 1) {
53
54 result = val1;
55
56 } else if (stat == 2) {
57
58 result = val2;
59
60 } else {
61
62 result = 0;
63
64 }
65
66 // send result to device B
67
68 SPI.beginTransaction(settingsB);
69
70 digitalWrite (slaveBPin, LOW);
71
72 SPI.transfer(result);
73
74 digitalWrite (slaveBPin, HIGH);
75
76 SPI.endTransaction();
77}

Contribute to Arduino

Join the community and suggest improvements to this article via GitHub. Make sure to read out contribution policy before making your pull request.

Missing something?

Check out our store and get what you need to follow this tutorial.

Suggest Changes

The content on docs.arduino.cc is facilitated through a public GitHub repository. You can read more on how to contribute in the contribution policy.
The Arduino documentation is licensed under the Creative Commons Attribution-Share Alike 4.0 license.