SPI flash support, with xiao nrf52 and portenta-h7

This commit is contained in:
cpq committed 2026-12-03 11:56:57 +00:00
1 parent 57e30ab2e9
commit f02ea9859e
17 files changed
+442 -17

No files matched your search

@@ -13,6 +13,15 @@
#define LED_3 PIN('K', 7) // On-board LED pin (blue)
#define LED LED_2 // Use green LED for blinking
// On-board 16 MB QSPI flash, used over plain SPI. Pins from Arduino's mbed-os,
// TARGET_PORTENTA_H7 PinNames.h: QSPI_FLASH1_*
#define FLASH_CS PIN('G', 6)
#define FLASH_SCK PIN('F', 10)
#define FLASH_MOSI PIN('D', 11) // IO0
#define FLASH_MISO PIN('D', 12) // IO1
#define FLASH_WP PIN('F', 7) // IO2, active low
#define FLASH_HOLD PIN('D', 13) // IO3, active low
#include <stm32h747xx.h>
#include <stdbool.h>
@@ -103,6 +112,50 @@ static inline void hal_gpio_output(uint16_t pin) {
HAL_GPIO_SPEED_HIGH, HAL_GPIO_PULL_NONE, 0);
}
// Bit-banged SPI to the on-board flash, mode 0. No SPI peripheral reaches the
// flash pins, they are wired for QUADSPI
static inline void hal_spi_init(void) {
uint16_t outs[] = {FLASH_CS, FLASH_WP, FLASH_HOLD, FLASH_SCK, FLASH_MOSI};
for (size_t i = 0; i < sizeof(outs) / sizeof(outs[0]); i++) {
hal_gpio_write(outs[i], outs[i] != FLASH_SCK); // SCK low, the rest high
hal_gpio_output(outs[i]);
}
hal_gpio_init(FLASH_MISO, HAL_GPIO_MODE_INPUT, HAL_GPIO_OTYPE_PUSH_PULL,
HAL_GPIO_SPEED_HIGH, HAL_GPIO_PULL_NONE, 0);
}
// struct mg_spi callbacks. spi is unused, there is one bus
static inline void hal_spi_begin(void *spi) {
(void) spi;
hal_gpio_write(FLASH_CS, false);
}
static inline void hal_spi_end(void *spi) {
(void) spi;
hal_gpio_write(FLASH_CS, true);
}
// Sends write and receives into read, len bytes. Either can be NULL, then
// 0xff is sent, or the input is dropped
static inline void hal_spi_txn(void *spi, uint8_t *write, uint8_t *read,
size_t len) {
GPIO_TypeDef *sck = hal_gpio_bank(FLASH_SCK), *mosi = hal_gpio_bank(FLASH_MOSI),
*miso = hal_gpio_bank(FLASH_MISO);
uint32_t sck_bit = BIT(PINNO(FLASH_SCK)), mosi_bit = BIT(PINNO(FLASH_MOSI)),
miso_bit = BIT(PINNO(FLASH_MISO));
(void) spi;
for (size_t i = 0; i < len; i++) {
uint32_t out = write == NULL ? 0xff : write[i], in = 0;
for (int b = 7; b >= 0; b--) {
mosi->BSRR = mosi_bit << ((out >> b) & 1 ? 0 : 16);
sck->BSRR = sck_bit; // Rising edge: the flash samples MOSI
in = (in << 1) | ((miso->IDR & miso_bit) ? 1 : 0);
sck->BSRR = sck_bit << 16; // Falling edge: the flash shifts out
}
if (read != NULL) read[i] = (uint8_t) in;
}
}
static inline void hal_rng_init(void) {
RCC->D2CCIP2R |= RCC_D2CCIP2R_RNGSEL_0; // RNG clock source pll1_q_ck
RCC->AHB2ENR |= RCC_AHB2ENR_RNGEN; // Enable RNG clock