Working with SPI - Arduino Programming using MATLAB, 1st Edition (2015)

Arduino Programming using MATLAB, 1st Edition (2015)

6. Working with SPI

In this chapter I'm going to explain how to work with SPI on Arduino board using MATLAB.

6.1 Getting Started

The Serial Peripheral Interface (SPI) is a communication bus that is used to interface one or more slave peripheral integrated circuits (ICs) to a single master SPI device; usually a microcontroller or microprocessor of some sort.

SPI in Arduino Uno board can be defined on the following pins:

· MOSI on Digital pin 11

· MISO on Digital pin 12

· SCK on Digital pin 13

· SS on Digital pin 10

If you have Arduino Mega, the following is its SPI pins:

· MOSI on Digital pin 51

· MISO on Digital pin 50

· SCK on Digital pin 52

· SS on Digital pin 53

In general, you learn SPI using MATLAB on this document, http://www.mathworks.com/help/supportpkg/arduinoio/spi-sensors.html . To access SPI on Arduino board from MATLAB, we can do the following steps:

· Open Arduino communication by creating arduino object

· Open SPI connection by calling spidev with passing SS pin, http://www.mathworks.com/help/supportpkg/arduinoio/ref/spidev.html

· To write and read SPI data, we can use writeRead with passing spidev object, http://www.mathworks.com/help/supportpkg/arduinoio/ref/writeread.html

In this chapter, we build a SPI Loopback app. Let's start!.

6.2 Demo : SPI Loopback

To develop SPI loopback, we can connect MOSI pin to MISO pin. This means you connect pin 11 to pin 12 using cable.

The following is a sample of wiring.

a5-2

On MATLAB, you can write thses scripts.

function [] = spi_loopback()

board = arduino();

finishup = onCleanup(@() exitprogram(board));

spi = spidev(board, 10);

k = 3;

m = 10;

n = 30;

disp('press Ctr-C to exit');

while1

disp('datain: ');

dataIn = [k m n];

disp(dataIn);

dataOut = writeRead(spi,dataIn);

disp('dataout: ');

disp(dataOut);

pause(1.5);

k = k + 1;

m = m + 1;

n = n + 1;

end

end

functionexitprogram(b)

clear b;

disp('program has exit');

end

Save these scripts into a file, callsed spi_loopback.m. Then, run this program on Command Windows of MATLAB.

>> spi_loopback

A sample output program can be seen in Figure below.

a5-1