SPI - Simples!
Page last updated
20 Feb 2010, by
Martin Spencer.
3
replies
I was getting very bored of typing spi.write(0xXX); repeatedly along with chip selects and deselects, waits etc etc. so why not bosh a couple of sub routines in and the SPI can be written to like this;
Write operation:
write(address,data);
Read Operation:
data = read(address);
simples! :D
Heres the code (obviously labels can be changed to suit) Insert waits as defined in the data sheet
void write(int address, int data) {
cs=0; //Select the deivce
_spi.write(address); //write the address of where the data is to be written first
_spi.write(data); //then send the data byte directly after it
cs=1; //deselect the device
}
int read(int address) {
cs=(0); //select the device
_spi.write(address); //select the register
_data = _spi.write(0x00); //send a dummy byte to retrive data
cs=1; //deselect the device
return _data; //return the data
}
To read data, you need to use spi.read(). write() will just return whether the write was successful, not the value read.
#
21 Feb 2010 . Edited: 21 Feb 2010
There is no 'spi.read()' function. from the MBed library:
SPI | A SPI Master, used for communicating with SPI slave devices |
Functions | |
SPI | Create a SPI master connected to the specified pins |
format | Configure the data transmission format |
frequency | Set the spi bus clock frequency |
write | Write to the SPI Slave and return the response
|
to read from SPI you first write the address on MOSI (the slave will return 0xXX)
Then write a dummy variable, on the first clock edge the slave will begin clocking data out on MISO.
spi.write(value) writes the value to MOSI and ignores data on MISO
variable = spi.write(value) writes the value to MOSI and returns the data on MISO.
using this on a write would indeed return the value just written, as you are addressing that register. Most devices have a 6 bit address and a read/not write bit which when set would return the contents of the register without overwriting it.
My bad, I confused it with I2C.
You need to log in to post a comment
To read data, you need to use spi.read(). write() will just return whether the write was successful, not the value read.