Simvik

Bit-bang SPI from a timing diagram

Read the clock polarity and phase off a sensor's timing diagram and drive the pins to match. A medium embedded C problem (Reading datasheets and schematics),…

medium · Reading datasheets and schematics · datasheets · spi · timing · bit-banging

A sensor's datasheet has no "SPI mode" in its text, only a timing diagram. Read off it:

  • CS falls to start a transfer and rises to end it. SCK idles high: it is high when CS falls, and must be high again before CS rises.
  • On each falling edge of SCK, the sensor puts its next bit on MISO, most significant bit first.
  • On each rising edge of SCK, the sensor samples MOSI, most significant bit first. MOSI must be stable before that edge.

Write spi_xfer(out): select the sensor, clock 8 bits out on MOSI while reading 8 bits in from MISO, deselect, and return the byte read. SCK is high when the function is called. The provided starter was written for another sensor, and it is wrong for this one.

Starter code

uint8_t spi_xfer(uint8_t out) {
  uint8_t in = 0;
  cs(0);
  for (int i = 7; i >= 0; i--) {
    mosi((out >> i) & 1);
    sck(1);
    in = (uint8_t)((in << 1) | miso());
    sck(0);
  }
  cs(1);
  return in;
}

Example tests

Read the WHO_AM_I register

xfer(0x8F, 0x6B);

Expected output:

sent 0x8F: sensor got 0x8F in 8 bits, read 0x6B

Learn it first

More Reading datasheets and schematics problems