Simvik

Driver: bring up SPI and read a sensor's ID

Configure an SPI master and its chip-select pin, then read one register from a sensor. A medium embedded C problem (SPI), run and graded in the browser.

medium · SPI · driver · registers · spi · chip-select

An ST motion sensor sits on SPI1, selected by PA4 (active low). Both peripherals are simulated like an STM32F4's: each change of PA4 shows up as gpioa: pin 4 low, and the bus reports mistakes such as a mode fault.

  • spi_init() makes PA4 an output that idles high (changing only PA4's bits), and enables SPI1 as a master in mode 0 (CPOL = 0, CPHA = 0), MSB first, with the clock divided by 16. There is no hardware NSS pin here: manage it in software with SSM and SSI, or the SPI faults as soon as it is enabled.
  • spi_xfer(b) sends one byte and returns the byte received at the same time. Wait for TXE before writing DR, and for RXNE before reading it.
  • imu_read(reg) reads one sensor register: pull chip select low, send reg | IMU_READ, send a dummy byte and keep what comes back, then release chip select.

Starter code

void spi_init(void) {
}

uint8_t spi_xfer(uint8_t b) {
  return 0;
}

uint8_t imu_read(uint8_t reg) {
  return 0;
}

Example tests

Read WHO_AM_I

spi_init();
printf("WHO_AM_I = 0x%02X\n", imu_read(IMU_WHO_AM_I));

Expected output:

gpioa: pin 4 high
gpioa: pin 4 low
gpioa: pin 4 high
WHO_AM_I = 0x6B

Learn it first

  • SPI · Clock modes, chip select, multiple devices and throughput.

More SPI problems