Write an SPI transfer function.
#include <stdint.h>
#include <stddef.h>
typedef struct { volatile uint32_t CR1, CR2, SR, DR; } spi_t;
#define SPI_SR_RXNE (1u << 0)
#define SPI_SR_TXE (1u << 1)
#define SPI_SR_BSY (1u << 7)
void cs_low(void);
void cs_high(void);
/* full duplex: every byte sent clocks one byte in */
int spi_transfer(spi_t *s, const uint8_t *tx, uint8_t *rx, size_t len, uint32_t timeout)
{
int rc = 0;
cs_low();
for (size_t i = 0; i < len; i++) {
uint32_t t = timeout;
while (!(s->SR & SPI_SR_TXE)) if (--t == 0) { rc = -1; goto out; }
*(volatile uint8_t *)&s->DR = tx ? tx[i] : 0xFF; /* dummy byte for read-only */
t = timeout;
while (!(s->SR & SPI_SR_RXNE)) if (--t == 0) { rc = -1; goto out; }
uint8_t b = *(volatile uint8_t *)&s->DR; /* always read to clear RXNE */
if (rx) rx[i] = b;
}
{ uint32_t t = timeout; while ((s->SR & SPI_SR_BSY) && --t) { } } /* last bit fully out */
out:
cs_high();
return rc;
}
/* typical register read from an SPI sensor: send address with the read bit, then clock out data */
int sensor_read_reg(spi_t *s, uint8_t reg, uint8_t *val)
{
uint8_t tx[2] = { (uint8_t)(reg | 0x80u), 0xFF }, rx[2];
int rc = spi_transfer(s, tx, rx, 2, 10000);
*val = rx[1]; /* rx[0] is clocked in during the address */
return rc;
}
Points: SPI is full duplex, so you must read a byte for every byte written (or RXNE/overrun errors build up); send dummy bytes to read; wait for BSY to clear before releasing chip select; set the right mode (CPOL/CPHA), bit order and clock speed for the device; use byte access to DR on parts with a FIFO so the peripheral does not send 16 bits; use DMA for long transfers.