/* Shared register defs + helpers for the hexapod dongle (STM32F030F4 @ 8 MHz). * Magic word at 0x20000000 survives a soft reset: the app sets it to ask * safeboot to enter flash mode. Both linker scripts keep RAM clear of it * (RAM ORIGIN 0x20000004). */ #ifndef DONGLE_COMMON_H #define DONGLE_COMMON_H #include #define REG(a) (*(volatile uint32_t *)(a)) #define REG8(a) (*(volatile uint8_t *)(a)) #define MAGIC_ADDR 0x20000000u #define MAGIC_FLASH 0xB00710ADu /* "BOOT LOAD": app -> safeboot flash */ #define APP_BASE 0x08001000u /* stage 2 starts here (page 4) */ #define APP_PAGE_LO 4 #define APP_PAGE_HI 15 /* 16 KB / 1 KB pages = 0..15 */ #define PAGE_SIZE 1024u /* RCC */ #define RCC_AHBENR REG(0x40021014) #define RCC_APB2ENR REG(0x40021018) #define RCC_APB2RSTR REG(0x4002100C) #define RCC_AHBRSTR REG(0x40021028) /* GPIO */ #define GPIOA 0x48000000u #define GPIOB 0x48000400u #define GPIOF 0x48001400u #define MODER(p) REG((p)+0x00) #define OTYPER(p) REG((p)+0x04) #define PUPDR(p) REG((p)+0x0C) #define IDR(p) REG((p)+0x10) #define BSRR(p) REG((p)+0x18) #define AFRH(p) REG((p)+0x24) /* USART1 */ #define USART1_CR1 REG(0x40013800) #define USART1_BRR REG(0x4001380C) #define USART1_ISR REG(0x4001381C) #define USART1_RDR REG(0x40013824) #define USART1_TDR REG(0x40013828) /* SysTick */ #define STK_CTRL REG(0xE000E010) #define STK_LOAD REG(0xE000E014) #define STK_VAL REG(0xE000E018) /* FLASH */ #define FLASH_KEYR REG(0x40022004) #define FLASH_SR REG(0x4002200C) #define FLASH_CR REG(0x40022010) #define FLASH_AR REG(0x40022014) static inline void uart_init8n1(void) /* USART1 PA9/PA10, 115200 8N1, 8 MHz */ { RCC_AHBENR |= (1u << 17); /* GPIOA */ RCC_APB2ENR |= (1u << 14); /* USART1 */ MODER(GPIOA) = (MODER(GPIOA) & ~((3u << 18) | (3u << 20))) | (2u << 18) | (2u << 20); AFRH(GPIOA) = (AFRH(GPIOA) & ~((0xFu << 4) | (0xFu << 8))) | (1u << 4) | (1u << 8); USART1_BRR = 69; USART1_CR1 = (1u << 0) | (1u << 2) | (1u << 3); } static inline void uart_putc(char c) { while (!(USART1_ISR & (1u << 7))) {} USART1_TDR = (uint8_t)c; } static inline void uart_puts(const char *s) { while (*s) uart_putc(*s++); } static inline int uart_getc(void) /* non-blocking, -1 if none */ { if (USART1_ISR & (1u << 5)) return (uint8_t)USART1_RDR; return -1; } static inline uint8_t uart_getc_block(void) { while (!(USART1_ISR & (1u << 5))) {} return (uint8_t)USART1_RDR; } static inline void systick_setup(void) { STK_LOAD = 8000 - 1; STK_VAL = 0; STK_CTRL = 5; } static inline void delay_ms(uint32_t ms) { systick_setup(); while (ms--) { while (!(STK_CTRL & 0x10000)) {} } STK_CTRL = 0; } #endif