</>EmbeddedInterview
← All problems · Drivers & Peripherals

Bit-Banged SPI Transfer (Mode 0)

Medium

Implement uint8_t spi_xfer(uint8_t out) that sends and receives one byte, MSB first, in SPI mode 0 (CPOL = 0, CPHA = 0) using three GPIO helper functions: sck(int level), mosi(int level) and miso(). The clock idles low. The test harness simulates a peripheral that samples MOSI on the rising edge and changes MISO on the falling edge.

Write your code on the right and press Run (or Ctrl + Enter). Hidden tests check your functions and print the result below the editor.

In mode 0, data must be valid before the rising edge. So for each bit: set MOSI, raise SCK, read MISO, lower SCK.

#include <stdio.h>
#include <stdint.h>

static int pin_sck, pin_mosi;
static uint8_t dev_rx, dev_tx = 0x3C;
static int dev_bit = 7;
static void sck(int level)
{
    if (!pin_sck && level) dev_rx = (uint8_t)(dev_rx << 1 | pin_mosi);
    if (pin_sck && !level && dev_bit > 0) dev_bit--;
    pin_sck = level;
}
static void mosi(int level) { pin_mosi = level ? 1 : 0; }
static int  miso(void)      { return (dev_tx >> dev_bit) & 1; }

uint8_t spi_xfer(uint8_t out)
{
    uint8_t in = 0;
    for (int i = 7; i >= 0; i--) {
        mosi((out >> i) & 1);      /* set data while SCK is low */
        sck(1);                    /* rising edge: both sides sample */
        in = (uint8_t)(in << 1 | miso());
        sck(0);                    /* falling edge: both sides shift */
    }
    return in;
}

SPI is just two shift registers connected in a loop: each clock pulse sends one bit and receives one bit, so a transfer is always full duplex. In mode 0 both sides sample on the rising edge and change data on the falling edge; the first bit must therefore be on MOSI before the first rising edge.

On real hardware add delays to meet the device's maximum clock and setup/hold times, and toggle chip select around the transfer. For mode 1 you would shift on the rising edge and sample on the falling edge instead. Bit-banging is useful when you run out of hardware SPI blocks or need an odd frame length.

solution.c
OutputPress Run to compile and test your code.
Show the hidden tests
/* ---- tests ---- */
static int fails;
#define CHECK(c) do { if (!(c)) { printf("FAIL line %d: %s\n", __LINE__, #c); fails++; } } while (0)
int main(void)
{
    uint8_t in = spi_xfer(0xA5);
    CHECK(dev_rx == 0xA5);
    CHECK(in == 0x3C);
    CHECK(pin_sck == 0);       /* clock idles low */
    puts(fails ? "Some tests failed" : "All tests passed");
    return fails != 0;
}