Standardize F4 baremetal

This commit is contained in:
Sergio R. Caprile 2023-02-10 15:53:55 -03:00
parent fbaaf89a21
commit 1cb99ea2fc
10 changed files with 123 additions and 173 deletions

View File

@ -1,60 +1,50 @@
# Download CMSIS header files from Github on demand
CMSIS_CORE_VERSION ?= 5.9.0 # ARM Cortex-M definitions
CMSIS_CORE_REPO ?= https://github.com/ARM-software/CMSIS_5
CMSIS_DEVICE_VERSION ?= v2.6.8 # ST MCU peripheral definitions
CMSIS_DEVICE_REPO ?= https://github.com/STMicroelectronics/cmsis_device_f4
CFLAGS ?= -W -Wall -Wextra -Werror -Wundef -Wshadow -Wdouble-promotion \
-Wformat-truncation -fno-common -Wconversion \
-g3 -Os -ffunction-sections -fdata-sections \
-I . -I cmsis_core/CMSIS/Core/Include -I cmsis_device_f4/Include \
-mcpu=cortex-m4 -mthumb -mfloat-abi=hard -mfpu=fpv4-sp-d16 $(EXTRA_CFLAGS)
CFLAGS = -W -Wall -Wextra -Werror -Wundef -Wshadow -Wdouble-promotion
CFLAGS += -Wformat-truncation -fno-common -Wconversion -Wno-sign-conversion
CFLAGS += -g3 -Os -ffunction-sections -fdata-sections
CFLAGS += -I. -Icmsis_core/CMSIS/Core/Include -Icmsis_f4/Include
CFLAGS += -mcpu=cortex-m4 -mthumb -mfloat-abi=hard -mfpu=fpv4-sp-d16
LDFLAGS ?= -Tlink.ld -nostdlib -nostartfiles --specs nano.specs -lc -lgcc -Wl,--gc-sections -Wl,-Map=$@.map
SOURCES = main.c syscalls.c cmsis_device_f4/Source/Templates/gcc/startup_stm32f429xx.s
# Mongoose-specific build flags and source code files
# Build options reference: https://mongoose.ws/documentation/#build-options
CFLAGS += -I../../.. -DMG_ARCH=MG_ARCH_NEWLIB -DMG_ENABLE_CUSTOM_MILLIS=1 -DMG_ENABLE_TCPIP=1 -DMG_ENABLE_PACKED_FS=1
SOURCES += ../../../mongoose.c ../../device-dashboard/net.c ../../device-dashboard/packed_fs.c
SOURCES = main.c syscalls.c sysinit.c
SOURCES += cmsis_f4/Source/Templates/gcc/startup_stm32f429xx.s # ST startup file. Compiler-dependent!
# Mongoose-specific source code files and build options. See https://mongoose.ws/documentation/#build-options
SOURCES += mongoose.c net.c packed_fs.c
CFLAGS += -DMG_ENABLE_TCPIP=1 -DMG_ARCH=MG_ARCH_NEWLIB -DMG_ENABLE_CUSTOM_MILLIS=1
CFLAGS += -DMG_ENABLE_CUSTOM_RANDOM=1 -DMG_ENABLE_PACKED_FS=1 $(CFLAGS_EXTRA)
ifeq ($(OS),Windows_NT)
RM = cmd /C del /Q /F /S
else
RM = rm -rf
endif
# Build flashable .bin file
all build example: firmware.bin
# .bin file is made from .elf file, by concatenating .text and .data sections
firmware.bin: firmware.elf
arm-none-eabi-objcopy -O binary $< $@
# .elf file is produced by compiling sources
firmware.elf: $(SOURCES) hal.h link.ld cmsis_core cmsis_device_f4
firmware.elf: cmsis_core cmsis_f4 $(SOURCES) hal.h link.ld
arm-none-eabi-gcc $(SOURCES) $(CFLAGS) $(LDFLAGS) -o $@
# Flash .bin file to the target board via the built-in debugger
flash: firmware.bin
st-flash --reset write $< 0x8000000
# Download ST's CMSIS headers with peripheral definitions
cmsis_device_f4/Source/Templates/gcc/startup_stm32f429xx.s: cmsis_device_f4
cmsis_device_f4:
git clone --depth 1 -b $(CMSIS_DEVICE_VERSION) $(CMSIS_DEVICE_REPO) $@
cmsis_core: # ARM CMSIS core headers
git clone --depth 1 -b 5.9.0 https://github.com/ARM-software/CMSIS_5 $@
cmsis_f4: # ARM CMSIS core headers
git clone --depth 1 -b v2.6.8 https://github.com/STMicroelectronics/cmsis_device_f4 $@
# Download ARM's CMSIS headers with core Cortex-M definitions
cmsis_core:
git clone --depth 1 -b $(CMSIS_CORE_VERSION) $(CMSIS_CORE_REPO) $@
# Requires env variable VCON_API_KEY set
# Automated remote test. Requires env variable VCON_API_KEY set. See https://vcon.io/automated-firmware-tests/
DEVICE_URL ?= https://dash.vcon.io/api/v3/devices/2
# Upload firmware to a remote test device
update: firmware.bin
curl --fail-with-body -su :$(VCON_API_KEY) $(DEVICE_URL)/ota --data-binary @$<
# Read serial port on a remote test device for 5 seconds, store in a
# temporary file, and check the output for expected patterns
test: EXTRA_CFLAGS += -DUART_DEBUG=UART1
test update: CFLAGS_EXTRA += -DUART_DEBUG=USART1
test: update
curl --fail-with-body -su :$(VCON_API_KEY) $(DEVICE_URL)/tx?t=5 | tee /tmp/output.txt
grep 'Ethernet: up' /tmp/output.txt # Check for network init
grep 'READY, IP:' /tmp/output.txt # Check for network init
grep 'MQTT connected' /tmp/output.txt # Check for MQTT connection success
clean:
@rm -rf firmware.* *.su cmsis_core cmsis_device_f4
$(RM) firmware.* *.su cmsis_core cmsis_f4

View File

@ -1,44 +1,3 @@
# Baremetal webserver on NUCLEO-F429ZI
# Baremetal web device dashboard on NUCLEO-F429ZI
This firmware uses MIP, an experimental TCP/IP stack of the Mongoose Network Library,
which implements the following:
- A complete [HTTP device dashboard](../../device-dashboard) with:
- User authentication
- Real-time device data graph
- Coninfiguration display and update
- MQTT communication with a remote MQTT server
- No dependencies: no HAL, no CMSIS, no RTOS
- Hand-written [mcu.h](mcu.h) header based on a [datasheet](https://www.st.com/resource/en/reference_manual/rm0090-stm32f405415-stm32f407417-stm32f427437-and-stm32f429439-advanced-armbased-32bit-mcus-stmicroelectronics.pdf)
- Interrupt-driven [Ethernet driver](../../../drivers/driver_stm32.c)
- Blue LED blinky, based on SysTick interrupt
- User button handler, turns off/on green LED, based on EXTI, interrupt-driven
- HardFault handler that blinks red LED
- Debug log on UART3 (st-link)
## Requirements
- [GNU make](http://mongoose.ws/tutorials/tools/#gnu-make)
- [ARM GCC](http://mongoose.ws/tutorials/tools/#arm-gcc)
- [stlink](http://mongoose.ws/tutorials/tools/#stlink) for flashing
The links above will send you to tutorials on how to install each of those tools in your workstation for Linux, Mac, and Windows.
## Usage
Plugin your Nucleo board into USB, and attach an Ethernet cable.
To build and flash:
```sh
$ make clean flash
```
To see debug log, use any serial monitor program like `picocom` at 115200 bps and configure it to insert carriage returns after line feeds:
```sh
$ picocom /dev/ttyACM0 -i -b 115200 --imap=lfcrlf
```
There is also a [detailed tutorial on this example](https://mongoose.ws/tutorials/stm32/nucleo-f746zg-baremetal/) but for the NUCLEO-F746ZG board
For more details and benchmark data on MIP, check the [F746ZG example](../nucleo-f746zg-baremetal/)
See https://mongoose.ws/tutorials/stm32/nucleo-f429zi-baremetal/

View File

@ -71,21 +71,8 @@ static inline void gpio_output(uint16_t pin) {
GPIO_PULL_NONE, 0);
}
#if 0
struct syscfg {
volatile uint32_t MEMRMP, PMC, EXTICR[4], RESERVED[2], CMPCR;
};
#define SYSCFG ((struct syscfg *) 0x40013800)
struct exti {
volatile uint32_t IMR, EMR, RTSR, FTSR, SWIER, PR;
};
#define EXTI ((struct exti *) 0x40013c00)
#endif
static inline void irq_exti_attach(uint16_t pin) {
uint8_t bank = (uint8_t) (PINBANK(pin)), n = (uint8_t) (PINNO(pin));
RCC->APB2ENR |= BIT(14); // Enable SYSCFG
SYSCFG->EXTICR[n / 4] &= ~(15UL << ((n % 4) * 4));
SYSCFG->EXTICR[n / 4] |= (uint32_t) (bank << ((n % 4) * 4));
EXTI->IMR |= BIT(n);
@ -96,21 +83,8 @@ static inline void irq_exti_attach(uint16_t pin) {
NVIC_EnableIRQ(irqvec);
}
#if 0
USART_TypeDef {
volatile uint32_t SR, DR, BRR, CR1, CR2, CR3, GTPR;
};
#define UART1 ((USART_TypeDef *) 0x40011000)
#define UART2 ((USART_TypeDef *) 0x40004400)
#define UART3 ((USART_TypeDef *) 0x40004800)
#endif
#define UART1 USART1
#define UART2 USART2
#define UART3 USART3
#ifndef UART_DEBUG
#define UART_DEBUG UART3
#define UART_DEBUG USART3
#endif
static inline void uart_init(USART_TypeDef *uart, unsigned long baud) {
@ -119,13 +93,13 @@ static inline void uart_init(USART_TypeDef *uart, unsigned long baud) {
uint16_t rx = 0, tx = 0; // pins
uint32_t freq = 0; // Bus frequency. UART1 is on APB2, rest on APB1
if (uart == UART1) freq = APB2_FREQUENCY, RCC->APB2ENR |= BIT(4);
if (uart == UART2) freq = APB1_FREQUENCY, RCC->APB1ENR |= BIT(17);
if (uart == UART3) freq = APB1_FREQUENCY, RCC->APB1ENR |= BIT(18);
if (uart == USART1) freq = APB2_FREQUENCY, RCC->APB2ENR |= BIT(4);
if (uart == USART2) freq = APB1_FREQUENCY, RCC->APB1ENR |= BIT(17);
if (uart == USART3) freq = APB1_FREQUENCY, RCC->APB1ENR |= BIT(18);
if (uart == UART1) tx = PIN('A', 9), rx = PIN('A', 10);
if (uart == UART2) tx = PIN('A', 2), rx = PIN('A', 3);
if (uart == UART3) tx = PIN('D', 8), rx = PIN('D', 9);
if (uart == USART1) tx = PIN('A', 9), rx = PIN('A', 10);
if (uart == USART2) tx = PIN('A', 2), rx = PIN('A', 3);
if (uart == USART3) tx = PIN('D', 8), rx = PIN('D', 9);
gpio_init(tx, GPIO_MODE_AF, GPIO_OTYPE_PUSH_PULL, GPIO_SPEED_HIGH, 0, af);
gpio_init(rx, GPIO_MODE_AF, GPIO_OTYPE_PUSH_PULL, GPIO_SPEED_HIGH, 0, af);
@ -147,17 +121,20 @@ static inline uint8_t uart_read_byte(USART_TypeDef *uart) {
return (uint8_t) (uart->DR & 255);
}
static inline void clock_init(void) { // Set clock frequency
SCB->CPACR |= ((3UL << 10 * 2) | (3UL << 11 * 2)); // Enable FPU
asm("DSB");
asm("ISB");
FLASH->ACR |= FLASH_LATENCY | BIT(8) | BIT(9); // Flash latency
RCC->PLLCFGR &= ~((BIT(17) - 1)); // Clear PLL multipliers
RCC->PLLCFGR |= (((PLL_P - 2) / 2) & 3) << 16; // Set PLL_P
RCC->PLLCFGR |= PLL_M | (PLL_N << 6); // Set PLL_M and PLL_N
RCC->CR |= BIT(24); // Enable PLL
while ((RCC->CR & BIT(25)) == 0) spin(1); // Wait until done
RCC->CFGR = (APB1_PRE << 10) | (APB2_PRE << 13); // Set prescalers
RCC->CFGR |= 2; // Set clock source to PLL
while ((RCC->CFGR & 12) == 0) spin(1); // Wait until done
static inline void rng_init(void) {
RCC->AHB2ENR |= RCC_AHB2ENR_RNGEN;
RNG->CR |= RNG_CR_RNGEN;
}
static inline uint32_t rng_read(void) {
while ((RNG->SR & RNG_SR_DRDY) == 0) (void) 0;
return RNG->DR;
}
#define UUID ((uint8_t *) UID_BASE) // Unique 96-bit chip ID. TRM 39.1
// Helper macro for MAC generation
#define GENERATE_LOCALLY_ADMINISTERED_MAC() \
{ \
2, UUID[0] ^ UUID[1], UUID[2] ^ UUID[3], UUID[4] ^ UUID[5], \
UUID[6] ^ UUID[7] ^ UUID[8], UUID[9] ^ UUID[10] ^ UUID[11] \
}

View File

@ -4,53 +4,39 @@
#include "hal.h"
#include "mongoose.h"
#define LED1 PIN('B', 0) // On-board LED pin (green)
#define LED2 PIN('B', 7) // On-board LED pin (blue)
#define LED3 PIN('B', 14) // On-board LED pin (red)
#define BTN1 PIN('C', 13) // On-board user button
#define LED1 PIN('B', 0) // On-board LED pin (green)
#define LED2 PIN('B', 7) // On-board LED pin (blue)
#define LED3 PIN('B', 14) // On-board LED pin (red)
#define LED LED2 // Use blue LED for blinking
#define BLINK_PERIOD_MS 1000 // LED blinking period in millis
static volatile uint64_t s_ticks, s_exti; // Counters
uint64_t mg_millis(void) { // Declare our own uptime function
return s_ticks; // Return number of milliseconds since boot
}
void HardFault_Handler(void) { // Escalated fault handler
gpio_output(LED3); // Setup red LED
for (;;) spin(2999999), gpio_toggle(LED3); // Blink LED infinitely
}
void SysTick_Handler(void) { // SyStick IRQ handler, triggered every 1ms
static volatile uint64_t s_ticks; // Milliseconds since boot
void SysTick_Handler(void) { // SyStick IRQ handler, triggered every 1ms
s_ticks++;
}
void EXTI15_10_IRQHandler(void) { // External interrupt handler
s_exti++;
if (EXTI->PR & BIT(PINNO(BTN1))) EXTI->PR = BIT(PINNO(BTN1));
gpio_write(LED1, gpio_read(BTN1)); // No debounce. Turn LED if button pressed
uint64_t mg_millis(void) { // Let Mongoose use our uptime function
return s_ticks; // Return number of milliseconds since boot
}
void SystemInit(void) { // Called automatically by startup code
clock_init(); // Set clock to 180MHz
SysTick_Config(SYS_FREQUENCY / 1000); // Increment s_ticks every ms
void mg_random(void *buf, size_t len) { // Use on-board RNG
for (size_t n = 0; n < len; n += sizeof(uint32_t)) {
uint32_t r = rng_read();
memcpy((char *) buf + n, &r, n + sizeof(r) > len ? len - n : sizeof(r));
}
}
static void timer_fn(void *arg) {
gpio_toggle(LED2); // Blink LED
bool up = ((struct mg_tcpip_if *) arg)->state == MIP_STATE_READY;
MG_INFO(("Ethernet: %s", up ? "up" : "down")); // Show network status
gpio_toggle(LED); // Blink LED
struct mg_tcpip_if *ifp = arg; // And show
const char *names[] = {"down", "up", "ready"}; // network stats
MG_INFO(("Ethernet: %s, IP: %M, rx:%u, tx:%u, dr:%u, er:%u",
names[ifp->state], mg_print_ip4, &ifp->ip, ifp->nrecv, ifp->nsent,
ifp->ndrop, ifp->nerr));
}
int main(void) {
gpio_output(LED1); // Setup green LED
gpio_output(LED2); // Setup blue LED
gpio_input(BTN1); // Set button to input
irq_exti_attach(BTN1); // Attach BTN1 to exti
uart_init(UART_DEBUG, 115200); // Initialise debug printf
MG_INFO(("Starting, CPU freq %g MHz", (double) SYS_FREQUENCY / 1000000));
static void ethernet_init(void) {
// Initialise Ethernet. Enable MAC GPIO pins, see
// https://www.farnell.com/datasheets/2014265.pdf section 6.10
uint16_t pins[] = {PIN('A', 1), PIN('A', 2), PIN('A', 7),
@ -58,30 +44,35 @@ int main(void) {
PIN('C', 5), PIN('G', 11), PIN('G', 13)};
for (size_t i = 0; i < sizeof(pins) / sizeof(pins[0]); i++) {
gpio_init(pins[i], GPIO_MODE_AF, GPIO_OTYPE_PUSH_PULL, GPIO_SPEED_INSANE,
GPIO_PULL_NONE, 11);
GPIO_PULL_NONE, 11); // 11 is the Ethernet function
}
NVIC_EnableIRQ(ETH_IRQn); // Setup Ethernet IRQ handler
RCC->APB2ENR |= BIT(14); // Enable SYSCFG
SYSCFG->PMC |= BIT(23); // Use RMII. Goes first!
RCC->AHB1ENR |= BIT(25) | BIT(26) | BIT(27); // Enable Ethernet clocks
RCC->AHB1RSTR |= BIT(25); // ETHMAC force reset
RCC->AHB1RSTR &= ~BIT(25); // ETHMAC release reset
NVIC_EnableIRQ(ETH_IRQn); // Setup Ethernet IRQ handler
SYSCFG->PMC |= SYSCFG_PMC_MII_RMII_SEL; // Use RMII. Goes first!
RCC->AHB1ENR |=
RCC_AHB1ENR_ETHMACEN | RCC_AHB1ENR_ETHMACTXEN | RCC_AHB1ENR_ETHMACRXEN;
}
struct mg_mgr mgr; // Initialise Mongoose event manager
mg_mgr_init(&mgr); // and attach it to the MIP interface
int main(void) {
gpio_output(LED); // Setup green LED
uart_init(UART_DEBUG, 115200); // Initialise debug printf
ethernet_init(); // Initialise ethernet pins
MG_INFO(("Starting, CPU freq %g MHz", (double) SystemCoreClock / 1000000));
struct mg_mgr mgr; // Initialise
mg_mgr_init(&mgr); // Mongoose event manager
mg_log_set(MG_LL_DEBUG); // Set log level
// Initialise Mongoose network stack
// Specify MAC address, and IP/mask/GW in network byte order for static
// IP configuration. If IP/mask/GW are unset, DHCP is going to be used
struct mg_tcpip_driver_stm32_data driver_data = {.mdc_cr = 4};
struct mg_tcpip_if mif = {.mac = {2, 0, 1, 2, 3, 5},
struct mg_tcpip_if mif = {.mac = GENERATE_LOCALLY_ADMINISTERED_MAC(),
.driver = &mg_tcpip_driver_stm32,
.driver_data = &driver_data};
mg_tcpip_init(&mgr, &mif);
mg_timer_add(&mgr, BLINK_PERIOD_MS, MG_TIMER_REPEAT, timer_fn, &mif);
MG_INFO(("Waiting until network is up..."));
MG_INFO(("MAC: %M. Waiting for IP...", mg_print_mac, mif.mac));
while (mif.state != MIP_STATE_READY) {
mg_mgr_poll(&mgr, 0);
}

View File

@ -0,0 +1 @@
../../../mongoose.c

View File

@ -0,0 +1 @@
../../../mongoose.h

View File

@ -0,0 +1 @@
../../device-dashboard/net.c

View File

@ -0,0 +1 @@
../../device-dashboard/packed_fs.c

View File

@ -53,7 +53,7 @@ int _getpid(void) {
int _write(int fd, char *ptr, int len) {
(void) fd, (void) ptr, (void) len;
if (fd == 1) uart_write_buf(UART1, ptr, (size_t) len);
if (fd == 1) uart_write_buf(UART_DEBUG, ptr, (size_t) len);
return -1;
}

View File

@ -0,0 +1,29 @@
// Copyright (c) 2023 Cesanta Software Limited
// All rights reserved
//
// This file contains essentials required by the CMSIS:
// uint32_t SystemCoreClock - holds the system core clock value
// SystemInit() - initialises the system, e.g. sets up clocks
#include "hal.h"
uint32_t SystemCoreClock = SYS_FREQUENCY;
void SystemInit(void) { // Called automatically by startup code
SCB->CPACR |= ((3UL << 10 * 2) | (3UL << 11 * 2)); // Enable FPU
asm("DSB");
asm("ISB");
FLASH->ACR |= FLASH_LATENCY | BIT(8) | BIT(9); // Flash latency, prefetch
RCC->PLLCFGR &= ~((BIT(17) - 1)); // Clear PLL multipliers
RCC->PLLCFGR |= (((PLL_P - 2) / 2) & 3) << 16; // Set PLL_P
RCC->PLLCFGR |= PLL_M | (PLL_N << 6); // Set PLL_M and PLL_N
RCC->CR |= BIT(24); // Enable PLL
while ((RCC->CR & BIT(25)) == 0) spin(1); // Wait until done
RCC->CFGR = (APB1_PRE << 10) | (APB2_PRE << 13); // Set prescalers
RCC->CFGR |= 2; // Set clock source to PLL
while ((RCC->CFGR & 12) == 0) spin(1); // Wait until done
RCC->APB2ENR |= RCC_APB2ENR_SYSCFGEN; // Enable SYSCFG
rng_init(); // Initialise random number generator
SysTick_Config(SystemCoreClock / 1000); // Sys tick every 1ms
}