Simvik

Configure a sensor over SPI from its datasheet

Pick the SPI mode and the fastest clock the sensor allows, then set its data rate and range from the register map, including a non-obvious field encoding. A…

hard · Reading datasheets and schematics · datasheets · driver · spi

Bring up the motion sensor on SPI1, working from the Datasheet excerpt below. Write imu_init(), which must:

  1. Make PA4 an output that deselects the sensor (high) before it starts driving the pin.
  2. Configure SPI1 as master in one of the sensor's modes, most significant bit first, with software slave management (SSM and SSI set), at the fastest SCK the sensor allows; then enable it.
  3. Read WHO_AM_I and return −1 if it is not 0x6B.
  4. Write CTRL1 for a 104 Hz output data rate and a ±4 g range, then return 0.

The helpers cs() and spi_xfer() under Provided do the byte transfers.

Datasheet excerpt

SPI interface (sensor datasheet)

ParameterValue
SPI modes0 (CPOL 0, CPHA 0) or 3 (CPOL 1, CPHA 1)
SCK frequency10 MHz maximum
Bit ordermost significant bit first
First bytebit 7: 1 = read, 0 = write; bits 6:0: register address
Following bytesdata, for consecutive registers

CTRL1 (0x10), read/write

BitsFieldValues
7:4ODR0000 power-down, 0001 12.5 Hz, 0010 26 Hz, 0011 52 Hz, 0100 104 Hz, 0101 208 Hz
3:2FSfull scale: 00 ±2 g, 01 ±16 g, 10 ±4 g, 11 ±8 g
1:0—reserved, write 00

WHO_AM_I (0x0F), read-only: 0x6B.

SPI1 (microcontroller reference manual)

SPI1 is on APB2, which runs at 84 MHz on this board. CR1 bits 5:3 BR: SCK = PCLK2 / 2^(BR+1), so 000 = /2, 001 = /4, 010 = /8, 011 = /16, 100 = /32.

Starter code

int imu_init(void) {
  GPIOA->BSRR = 1u << CS_PIN;
  GPIOA->MODER = (GPIOA->MODER & ~(3u << (CS_PIN * 2))) | (1u << (CS_PIN * 2));
  SPI1->CR1 = SPI_CR1_MSTR | SPI_CR1_BR(2) | SPI_CR1_SSM | SPI_CR1_SSI;
  SPI1->CR1 |= SPI_CR1_SPE;

  cs(1);
  spi_xfer(0x0F);
  uint8_t id = spi_xfer(0x00);
  cs(0);
  if (id != 0x6B) return -1;

  cs(1);
  spi_xfer(0x10);
  spi_xfer(0x44);
  cs(0);
  return 0;
}

Example tests

Bring-up

printf("imu_init() = %d\n", imu_init());
show_clock();

Expected output:

gpioa: pin 4 high
gpioa: pin 4 low
gpioa: pin 4 high
gpioa: pin 4 low
imu: write 0x10 = 0x48
gpioa: pin 4 high
imu_init() = 0
SCK 5250000 Hz

Learn it first

More Reading datasheets and schematics problems