Hardware Reference
In-Depth Information
Setting Up a Master SPI Device
For Listing 10-1, two Arduino-compatible boards are required (Unos were used for the example). For other Arduinos,
refer to the board's pin map and connect to the appropriate pins. You'll also need an external LED because the SPI
communication uses pin 13. The SPI master simplifies the pin mapping by setting the pins automatically, regardless
of the board. SPI is electrically a straight-through protocol. The four standard lines of SPI—MISO (master in slave out),
MOSI (master out slave in), SCK (serial clock), and SS (slave select)—should be wired together. You'll also need to
share a common ground between devices and power, either separately or from one board to another. Table 10-4
describes the standard pin configuration.
Table 10-4. SPI Default Pin Configuration
Master
Slave
MOSI
Output
MOSI
Input
MISO
Input
MISO
Output
SCK
Output
SCK
Input
SS
Output
SS
Input
The SS line on the master is not tied to any particular pin, and multiple can be used at the same time, one for
each additional device. When using different SS connections, the original SS needs to be declared as an output. If the
SS is an input and drops low, the device will lose its configuration as a master and become a slave.
Listing 10-1 includes code for both an SPI master and slave. The master uses the SPI library, and the slave is
written directly addressing the SPI registers on the Arduino. The code for the slave will be recycled for the second
example, later in the chapter. Before beginning, you should mark the Arduinos as designating master or slave.
A marker with ink that comes off easily with rubbing alcohol can be used on the USB connector.
Listing 10-1. SPI Master Sketch
#include <SPI.h> // Include the SPI library for master
byte dataToSend;
byte dataToReceive;
boolean blink = LOW;
void setup() {
pinMode(8,OUTPUT); // Blink
pinMode(10,OUTPUT); // Set the slave select pin to output for the master
digitalWrite(10, HIGH); // Set the slave select pin high
SPI.begin(); // Start SPI
Serial.begin(115200);
delay(500); // Allow connected devices to initialize
}// End setup
void loop() {
while (Serial.available() > 0) {
dataToSend = Serial.read(); // Read a byte in from serial
transferSPI(dataToSend); // Sent that byte
}
 
 
Search WWH ::




Custom Search