I have a question about SPI bus. I often see in some libraries that I found, but I can't understand how it works.
Quick examples from one library I found. Writing by SPI:
static void nRF24_WriteRegister(uint8_t reg, uint8_t val)
{
uint8_t tmp[2];
tmp[0] = NRF24_CMD_W_REGISTER | reg;
tmp[1] = val;
NRF24_CSN_LOW;
nRF24_SendSpi(tmp, 2);
NRF24_CSN_HIGH;
}
How it works, if we are putting to the same frame register(which we are writing to) and data to this register?
But even more confusing for me is reading from SPI:
static uint8_t nRF24_ReadRegister(uint8_t reg)
{
uint8_t result;
reg = NRF24_CMD_R_REGISTER | reg;
NRF24_CSN_LOW;
nRF24_SendSpi(®, 1);
nRF24_ReadSpi(&result, 1);
NRF24_CSN_HIGH;
return result;
}
Why do we have to send first some info and then read?
The SPI device contains a set of registers. Each register has an address and a value. The register values may be read and/or written by the master. The SPI device needs to know which register address the master is reading/writing. So the protocol is that the master first writes the register address, then subsequently reads/writes the register value. See the device datasheet for details about the available registers and the read/write protocol.
In your first example, nRF24_SendSpi(tmp, 2);
writes two bytes, first the register address and then the register value.
In your second example, nRF24_SendSpi(®, 1);
writes one byte, the register address. Then nRF24_ReadSpi(&result, 1);
reads one byte, the register value.
If the protocol did not start with writing the register address, then the SPI device would not know which register the master is trying to read/write.