Slave Library (I2C and SPI)

From Stm32World Wiki
Jump to navigation Jump to search
Library layers

Quite often an STM32 is used as a "smart peripheral" for another processor: a sensor front end, an I/O expander, a motor controller and so on. The host then expects it to behave like any other chip on the bus: a set of registers that can be read and written at an address.

Writing such a slave by hand is surprisingly fiddly. The protocol state machine, register pointer, auto increment, multi byte values that must not change half way through a read and bytes that were prefetched but never sent all have to be dealt with, and then it has to be done again for the next bus.

The slavelib library takes care of all of that. The application describes its registers in a table (the register map) and the library does the rest. The same register map can be served over I²C and SPI (UART is planned).

The library is split in three parts:

  • Core (slave.c) - the register map engine. Knows nothing about buses.
  • Protocol layers (slave_i2c.c, slave_spi.c) - turn bus events into register reads and writes.
  • Ports - the glue between a protocol layer and the actual peripheral driver (here the STM32 HAL).

The core and the protocol layers are plain portable C. They never include a HAL header or touch hardware, so the same code will run on other microcontrollers (an RP2350 port is planned). Only the port is MCU specific.

Features

  • Register map in a const table, sorted by address and validated at init.
  • 8 or 16 bit register addresses.
  • Four kinds of registers:
    • variable - points to a variable, size taken from the variable.
    • variable with notify - same, with a function called after the master has written it.
    • function - read and/or write handled by functions (computed values, fifos, commands).
    • memory - a buffer of any size mapped at an address range.
  • Read only, write only or read/write per register. Violations are counted.
  • Little or big endian on the wire per register.
  • Auto increment across registers, or fixed address (fifo style) per register.
  • Multi byte variables are snapshotted: a read returns a consistent value, and a write is committed only when the master leaves the register.
  • Unmapped addresses read as a fill byte and ignore writes.
  • Prefetched bytes the master never clocked out are given back, so the next read continues where the master really stopped.
  • Several slaves on different peripherals at the same time.
  • Callbacks are forwarded from the application's own HAL callbacks: no HAL register callbacks, nothing added to stm32xx_it.c.

Register Map

The register map used by the examples

The register map is an array of slave_reg_t, built with four macros:

Macro Use
SLAVE_REG_VAR(addr, var, flags) Register backed by a variable. Size is sizeof(var).
SLAVE_REG_VAR_NOTIFY(addr, var, flags, fn) Same, fn is called after a write has been committed.
SLAVE_REG_FN(addr, size, read_fn, write_fn, flags) Handled by functions. Either may be NULL.
SLAVE_REG_MEM(addr, buf, flags, notify) Memory region. Bytes are read and written directly in the buffer; notify gets the written range.

Flags:

Flag Meaning
SLAVE_RO, SLAVE_WO, SLAVE_RW Access rights.
SLAVE_BE Big endian on the wire (variables of size 2, 4 or 8). Default is little endian.
SLAVE_NOINC The address does not advance (fifo register).

The register map from the examples looks like this:

static const uint8_t reg_who_am_i = 0x5a;
static uint16_t reg_version = 0x0102;
static uint8_t reg_ctrl;
static uint32_t reg_le32;
static uint32_t reg_be32;
static uint8_t reg_memory[256];

static const slave_reg_t slave_map[] = {
    SLAVE_REG_VAR(0x0000, reg_who_am_i, SLAVE_RO),
    SLAVE_REG_VAR(0x0001, reg_version, SLAVE_RO | SLAVE_BE),
    SLAVE_REG_VAR_NOTIFY(0x0010, reg_ctrl, SLAVE_RW, ctrl_written),
    SLAVE_REG_FN(0x0020, 4, uptime_read, NULL, SLAVE_RO),
    SLAVE_REG_FN(0x0030, 1, fifo_out_read, NULL, SLAVE_RO | SLAVE_NOINC),
    SLAVE_REG_FN(0x0040, 1, NULL, fifo_in_write, SLAVE_WO | SLAVE_NOINC),
    SLAVE_REG_FN(0x0050, 4, NULL, cmd_write, SLAVE_WO),
    SLAVE_REG_VAR(0x0060, reg_le32, SLAVE_RW),
    SLAVE_REG_VAR(0x0064, reg_be32, SLAVE_RW | SLAVE_BE),
    SLAVE_REG_MEM(0x1000, reg_memory, SLAVE_RW, memory_written),
};

Read and write functions get the byte offset inside the register and a length, and return 0 on success:

static int uptime_read(slave_t *s, const slave_reg_t *reg, uint16_t offset, uint8_t *buf, uint16_t len)
{
    uint32_t uptime = HAL_GetTick();
    memcpy(buf, (uint8_t *) &uptime + offset, len);
    return 0;
}

static void ctrl_written(slave_t *s, const slave_reg_t *reg, uint16_t offset, uint16_t len)
{
    // reg_ctrl has a new value
}

All of these are called from interrupt context, so keep them short.

The map is passed to the core together with a small shadow buffer, which must be at least as large as the largest variable register (it holds the snapshots):

static slave_t slave;
static uint8_t slave_shadow[8];

static const slave_config_t slave_config = {
    .regs = slave_map,
    .reg_count = sizeof(slave_map) / sizeof(slave_map[0]),
    .addr_width = 2,                // 16 bit register addresses
    .fill = 0xff,                   // returned for unmapped addresses
    .shadow = slave_shadow,
    .shadow_size = sizeof(slave_shadow),
    .lock = slave_port_i2c_lock,    // optional, see below
    .unlock = slave_port_i2c_unlock,
    .ctx = &slave_port,
};

if (slave_init(&slave, &slave_config) != SLAVE_OK) {
    // map not sorted, registers overlap, bad flags...
}

When the application itself reads or writes a multi byte variable that is in the map, it should do so between slave_lock() and slave_unlock(), so the master never sees half an update. slave_errors() returns the number of access violations so far.

I²C

I²C transactions

The I²C protocol is the one used by most I²C sensors and EEPROMs: the first byte(s) after the address set the register pointer, the following bytes are written from there. A read sets the pointer, then a repeated start switches to reading. A read without the pointer bytes continues where the last transaction stopped.

The STM32 port (slave_port_i2c.c) uses the HAL listen mode with one byte sequential transfers, so every byte is handled as it arrives. Clock stretching must be enabled. In CubeMX enable the I²C event and error interrupts for the slave peripheral, then start it:

static slave_i2c_t slave_i2c;
static slave_port_i2c_t slave_port;

slave_init(&slave, &slave_config);
slave_i2c_init(&slave_i2c, &slave);
slave_port_i2c_start(&slave_port, &hi2c4, &slave_i2c, 0x42);   // 7 bit address

The port does not define the HAL callbacks itself. The application keeps them in main.c and forwards them; each function returns true if the handle belonged to a slave port, so other I²C peripherals can still be handled in the same callback:

/* USER CODE BEGIN 4 */

void HAL_I2C_AddrCallback(I2C_HandleTypeDef *hi2c, uint8_t direction, uint16_t addr_match)
{
    if (slave_port_i2c_addr(hi2c, direction, addr_match)) {
        return;
    }
}

void HAL_I2C_SlaveRxCpltCallback(I2C_HandleTypeDef *hi2c)
{
    if (slave_port_i2c_rx_cplt(hi2c)) {
        return;
    }
}

void HAL_I2C_SlaveTxCpltCallback(I2C_HandleTypeDef *hi2c)
{
    if (slave_port_i2c_tx_cplt(hi2c)) {
        return;
    }
}

void HAL_I2C_ListenCpltCallback(I2C_HandleTypeDef *hi2c)
{
    if (slave_port_i2c_listen_cplt(hi2c)) {
        return;
    }
}

void HAL_I2C_ErrorCallback(I2C_HandleTypeDef *hi2c)
{
    if (slave_port_i2c_error(hi2c)) {
        return;
    }
}

/* USER CODE END 4 */

SPI

SPI frames: a read request followed by the data, with the next command pipelined

SPI is different. The master clocks at full speed and there is no clock stretching, so there is no time to look up a register between two bytes. The SPI protocol is therefore frame based: a frame is everything between SS going low and SS going high.

Frame (MOSI) Meaning
0x02 addr[w] data... Write the data starting at addr.
0x03 addr[w] len_hi len_lo Read request for len bytes from addr.
0x00 or 0xff (or empty) Nop.

w is the register address width (1 or 2 bytes, MSB first). A read takes two frames. While SS is high the slave processes the request and prepares the data, and in the next frame the data is clocked out on MISO. That second frame may carry the next command on MOSI (pipelining), or nop bytes. If the master clocks fewer bytes than it asked for, the register pointer is moved back so nothing is lost.

The master must leave SS high long enough for the slave to handle the end of frame interrupt and prepare the data.

The STM32 port (slave_port_spi.c) keeps a full duplex transfer armed all the time and uses the SS pin as a GPIO with EXTI on both edges. On the rising edge it stops the transfer, hands the received bytes to the protocol layer and re-arms with the prepared transmit buffer. It has two modes, picked automatically:

  • Interrupt - HAL_SPI_TransmitReceive_IT(). Every byte goes through the SPI interrupt. On an STM32H723 at 550 MHz this keeps up to 16 Mbit/s.
  • DMA - used when CubeMX has linked RX and TX DMA streams to the SPI handle. One interrupt per frame. Tested at 32 Mbit/s with no noticeable CPU load. On the H7 the port struct (which holds the DMA buffers) must be in RAM the DMA can reach (not DTCM). With the D-cache enabled the port does the cache maintenance.

CubeMX setup for the slave: SPI full duplex slave, 8 bit, software NSS; the SS pin as GPIO_EXTI, rising and falling edge, pull-up. Give the EXTI a lower priority (higher number) than the SPI interrupt.

static slave_spi_t slave_spi;
static slave_port_spi_t slave_port;     // DMA mode: must be DMA reachable

slave_init(&slave, &slave_config);
slave_spi_init(&slave_spi, &slave);
slave_port_spi_start(&slave_port, &hspi4, SPI4_SS_GPIO_Port, SPI4_SS_Pin, &slave_spi);

And the forwarded callbacks:

/* USER CODE BEGIN 4 */

void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin)
{
    if (slave_port_spi_exti(GPIO_Pin)) {
        return;
    }
}

void HAL_SPI_TxRxCpltCallback(SPI_HandleTypeDef *hspi)
{
    if (slave_port_spi_txrx_cplt(hspi)) {
        return;
    }
}

void HAL_SPI_ErrorCallback(SPI_HandleTypeDef *hspi)
{
    if (slave_port_spi_error(hspi)) {
        return;
    }
}

/* USER CODE END 4 */

Adding the Library to a Project

The library is a CMake static library. With a CubeMX generated CMake project (or a Pico SDK project), put the src folder in the project (a symlink works fine) and add it in CMakeLists.txt:

add_subdirectory(slave)
target_link_libraries(${CMAKE_PROJECT_NAME} slave::slave)

Unused protocol layers can be left out with set(SLAVE_SPI OFF) or set(SLAVE_I2C OFF) before add_subdirectory(). The port files go in Core/Src and Core/Inc of the project.

Examples

Both examples run on a single STM32H723 board: one peripheral is the master and another is the slave, connected with jumper wires. Every 2 seconds the master runs the same suite of 17 tests against the register map above (bursts, short reads, fifos, endianness, writes across registers, memory blocks, gaps, access violations) and prints the result on the UART, together with a main loop counter to show how much CPU time is left.

Example Master Slave Wiring Result
I²C I2C1 (PB6 SCL, PB7 SDA) I2C4 (PB8 SCL, PB9 SDA), address 0x42 PB6-PB8, PB7-PB9, internal pull-ups 17/17 at 1 MHz (Fast Mode Plus)
SPI SPI1 (PA4 SS, PA5-PA7), DMA SPI4 (PE11 SS, PE12-PE14), DMA PA4-PE11, PA5-PE12, PA6-PE13, PA7-PE14 17/17 in 3 ms at 32 Mbit/s

At 64 Mbit/s the master reads MISO one bit late. The slave's output delay plus the jumper wires take longer than half a clock period, so 32 Mbit/s is the practical limit for this setup.

The library also has host tests (make -C tests test) that run the core and both protocol layers on a PC with the address and undefined behaviour sanitizers.

Miscellaneous Links