Communicating with EEPROM Using SPI bus
This example shows how to communicate with EEPROM AT25080A on Aardvark's I2C/SPI Activity Board over the Serial Peripheral Interface (SPI) bus.
To begin, create an SPI object. For this example, we are using Aardvark's I2C/SPI Activity Board which has both board index and address as 0. To connect the computer to the SPI bus, a USB-I2C/SPI adaptor from Aardvark is used. For SPI object creation, this translates to:
Vendor
= aardvarkBoardIndex
= 0Port
= 0
eeprom = spi('aardvark',0,0);
disp(eeprom);
SPI Object : Adapter Settings BoardIndex: 0 BoardSerial: 2237727782 VendorName: aardvark Communication Settings BitRate: 1000000 Hz ChipSelect: 0 ClockPhase: FirstEdge ClockPolarity: IdleLow Port: 0 Communication State ConnectionStatus: Disconnected Read/Write State TransferStatus: Idle
Before you can perform a read or write operation, you must connect the SPI object to the device using the connect
function. You can verify that the object has been successfully connected, by checking its ConnectionStatus
property. Once connected to the device, the property ConnectionStatus
is automatically updated to be Connected
.
connect(eeprom); eeprom.ConnectionStatus
ans = Connected
SPI operates in full duplex mode. Hence for any read/write operation, data is always transferred in both directions. This can be illustrated with a simple task of writing 'Hello' to EEPROM and reading it back.
The EEPROM's datasheet specifies the following for reading and writing data:
The chip should be write-enabled before writing anything to it.The chip can be write-enabled by writing
6
to it. NOTE: If the chip is not write-enabled, it will ignore the write instruction and will return to the standby state
Data should be written to the chip in the following format:
[Write_Command Upper_Byte_Address Lower_Byte_Address data1 data2 ...]
The Write_Command for this EEPROM is 2.
Data should be written to the chip in the following format to read it back correctly:
[Read_Command Upper_Byte_Address Lower_Byte_Address zeros(1,size of data to be read back)]
The Read_Command for this EEPROM is 3.
Write-enable the eeprom
write(eeprom,6);
Write 'Hello' at the 0th address of EEPROM using the write
function.
dataToWrite = [2 0 0 double('Hello')];
write(eeprom, dataToWrite);
We can now read data back from EEPROM.
dataToWrite = [3 0 0 zeros(1,5)]; returnedData = writeAndRead(eeprom, dataToWrite);
The data returned is:
Bytes 1:3 - Don't care
Fourth byte onwards - Data read back from EEPROM
In this case, the data read back is:
char(returnedData(4:end))
ans = Hello
Disconnect the SPI object and remove it from memory and the workspace.
disconnect(eeprom);
clear('eeprom');