SPI Module¶
Note
Features¶
There are a few pre-defined SPI interfaces:
SPI_Sensor
: Connected to the on board sensorsSPI_Touch
: Connected to the LCD Touch controller
Sending Data¶
The following code demonstrates how to set a register of the 6-Axis sensor by sending data directly to it.
// Set Chip Select here
// Write register address and data to sensor
uint8_t data[2] = { /* Register: */ 0x4E, /* Data: */ 0x0F };
if (R_SUCCESS(SPI_Write(SPI_Sensor, data, sizeof(data)))) {
// Successfully sent data
}
// Unset Chip Select here
-
result_t SPI_Write(SPI_Handle_t handle, const uint8_t *buffer, size_t size)¶
Writes data to the SPI interface.
- Parameters
buffer – Buffer to send data from
size – Buffer size
- Returns
Status result
Receiving Data¶
The following code shows how to directly read data from e.g a RAM connected over SPI which doesn’t need any setup commands.
// Read data
uint8_t data[4] = { };
if (R_SUCCESS(SPI_Read(SPI_RAM, data, sizeof(data)))) {
// Successfully read data
}
-
result_t SPI_Read(SPI_Handle_t handle, uint8_t *buffer, size_t size)¶
Reads data from the SPI interface.
- Parameters
buffer – Buffer to store received data in
size – Buffer size
- Returns
Status result
Sending and receiving data simultaneously¶
Many sensors and other more complex ICs connected over SPI first expect the address of the register that should be read to be sent before reporting back that register’s value.
Important
Since we’re writing and reading data at the same time, while sending out the first byte of address register, the sensor doesn’t repond yet
so we’re reading a 0x00 byte. After the address is sent, since we want to receive data from the sensor now, the clock needs to be generated again for
another byte. That’s why we have to send two bytes even though we only need to send one byte and receive one byte. Since the first byte of the receive buffer
has been filled already too now, the actual data from the sensor can be found in the second position of the receivedData
array.
00 01
Send Buffer : | 0xF5 | 0x00 |
Receive Buffer : | 0x00 | 0x42 |
// Set Chip Select here
// Write WHO_AM_I register address and data to sensor and at the same time receive the sensor's answer
uint8_t registerAddress[2] = { /* Register: */ 0xF5, 0x00 };
uint8_t receivedData[2] = { 0x00, 0x00 };
if (R_SUCCESS(SPI_WriteRead(SPI_Sensor, registerAddress, receivedData, sizeof(registerAddress)))) {
// Successfully sent and received data
if (receivedData[1] == 0x42) {
LOG_Info("Received correct device ID!");
}
}
// Unset Chip Select here
-
result_t SPI_WriteRead(SPI_Handle_t handle, uint8_t *read_buffer, const uint8_t *write_buffer, size_t size)¶
Writes and reads data simultaneously to/from the SPI interface.
- Parameters
read_buffer – Buffer to read data into
write_buffer – Buffer to send data from
size – Buffer size
- Returns
Status result