What an SPI mode means
Turn an SPI mode number into the clock's idle level and the edge that samples data. An easy embedded C problem (SPI), run and graded in the browser.
easy · SPI · spi · modes
SPI has four modes, made of two bits: CPOL (bit 1), the clock's idle level, and CPHA (bit 0), which edge samples the data: 0 = the first (leading) edge after chip select, 1 = the second (trailing) edge.
Write spi_mode_info(mode, idle_high, sample_rising): set *idle_high to 1 if the clock idles high, and *sample_rising to 1 if data is sampled on the rising edge, 0 if on the falling edge.
Remember that when the clock idles high, its first edge is a falling one.
Starter code
void spi_mode_info(int mode, int *idle_high, int *sample_rising) {
*idle_high = (mode >> 1) & 1;
*sample_rising = !(mode & 1); // leading edge = rising?
}Example tests
Modes 0 and 1
show(0);
show(1);Expected output:
mode 0: idles low, samples on the rising edge
mode 1: idles low, samples on the falling edgeMode 3
show(3);Expected output:
mode 3: idles high, samples on the rising edgeLearn it first
- SPI · Clock modes, chip select, multiple devices and throughput.
More SPI problems
- 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: 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.
- 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.