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 withSSMandSSI, 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 forTXEbefore writingDR, and forRXNEbefore reading it.imu_read(reg)reads one sensor register: pull chip select low, sendreg | 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 = 0x6BLearn it first
- SPI · Clock modes, chip select, multiple devices and throughput.
More SPI problems
- What an SPI mode means · Turn an SPI mode number into the clock's idle level and the edge that samples data.
- Split a flash write at page boundaries · Cut a write into Page Program commands that never cross a page.
- Feed a daisy chain · Send bytes to a chain of 74HC595s so each chip shows its own pattern.
- Read registers in a burst · Read several registers with one command, setting the read bit and skipping the command's reply.
- Driver: read an accelerometer in one burst · Power a sensor up over SPI and read its three axes in one chip-select assertion.
- Fix: the sensor ignores its configuration · A register write releases chip select while the last byte is still being clocked out.
- Smartwatch: pixels for the display · Pack a 24-bit colour into the display's 16-bit RGB565 format, in the order SPI sends it.