From 056e0b6293d140b5e03d8cc237796c52a2a6ddbb Mon Sep 17 00:00:00 2001 From: Damien George Date: Tue, 14 Aug 2018 22:05:20 +1000 Subject: [PATCH] stm32/spi: Add implementation of low-level SPI protocol. Can be used, for example, to configure external SPI flash using a hardware SPI interface (code to be put in a board's bdev.c file): STATIC const spi_proto_cfg_t hard_spi_bus = { .spi = &spi_obj[5], .baudrate = 10000000, .polarity = 0, .phase = 0, .bits = 8, .firstbit = SPI_FIRSTBIT_MSB, }; STATIC mp_spiflash_cache_t spi_bdev_cache; const mp_spiflash_config_t spiflash_config = { .bus_kind = MP_SPIFLASH_BUS_SPI, .bus.u_spi.cs = pin_A0, .bus.u_spi.data = (void*)&hard_spi_bus, .bus.u_spi.proto = &spi_proto, .cache = &spi_bdev_cache, }; spi_bdev_t spi_bdev; --- ports/stm32/spi.c | 31 +++++++++++++++++++++++++++++++ ports/stm32/spi.h | 11 +++++++++++ 2 files changed, 42 insertions(+) diff --git a/ports/stm32/spi.c b/ports/stm32/spi.c index d090181483..411083bf29 100644 --- a/ports/stm32/spi.c +++ b/ports/stm32/spi.c @@ -563,3 +563,34 @@ const spi_t *spi_from_mp_obj(mp_obj_t o) { mp_raise_TypeError("expecting an SPI object"); } } + +/******************************************************************************/ +// Implementation of low-level SPI C protocol + +STATIC int spi_proto_ioctl(void *self_in, uint32_t cmd) { + spi_proto_cfg_t *self = (spi_proto_cfg_t*)self_in; + + switch (cmd) { + case MP_SPI_IOCTL_INIT: + spi_set_params(self->spi, 0xffffffff, self->baudrate, + self->polarity, self->phase, self->bits, self->firstbit); + spi_init(self->spi, false); + break; + + case MP_SPI_IOCTL_DEINIT: + spi_deinit(self->spi); + break; + } + + return 0; +} + +STATIC void spi_proto_transfer(void *self_in, size_t len, const uint8_t *src, uint8_t *dest) { + spi_proto_cfg_t *self = (spi_proto_cfg_t*)self_in; + spi_transfer(self->spi, len, src, dest, SPI_TRANSFER_TIMEOUT(len)); +} + +const mp_spi_proto_t spi_proto = { + .ioctl = spi_proto_ioctl, + .transfer = spi_proto_transfer, +}; diff --git a/ports/stm32/spi.h b/ports/stm32/spi.h index 41e7a47e78..885fb0bd6f 100644 --- a/ports/stm32/spi.h +++ b/ports/stm32/spi.h @@ -26,6 +26,7 @@ #ifndef MICROPY_INCLUDED_STM32_SPI_H #define MICROPY_INCLUDED_STM32_SPI_H +#include "drivers/bus/spi.h" #include "dma.h" typedef struct _spi_t { @@ -34,6 +35,15 @@ typedef struct _spi_t { const dma_descr_t *rx_dma_descr; } spi_t; +typedef struct _spi_proto_cfg_t { + const spi_t *spi; + uint32_t baudrate; + uint8_t polarity; + uint8_t phase; + uint8_t bits; + uint8_t firstbit; +} spi_proto_cfg_t; + typedef struct _pyb_spi_obj_t { mp_obj_base_t base; const spi_t *spi; @@ -53,6 +63,7 @@ extern SPI_HandleTypeDef SPIHandle6; extern const spi_t spi_obj[6]; +extern const mp_spi_proto_t spi_proto; extern const mp_obj_type_t pyb_spi_type; extern const mp_obj_type_t machine_soft_spi_type; extern const mp_obj_type_t machine_hard_spi_type;