Arm Cortex-M Startup from Scratch
In this tutorial I would be using STM32 NUCLEO F767Zi, However you can use whichever MCU as you desire. The concepts are broadly applicable. Also note that basic C language knowledge is required/
First, we will try to build minimal firmware to put on the MCU.
Let's start by asking the question what happens when the MCU is turned on or is set to reset.
Let's get familiar with vector table first.
A vector table is a set of addresses that tells MCU where to go when the exception or interrupt occurrs. For the ARM Cortex-M, a vector table is usually placed at the start of Embedded flash. A vector table is required because CPU needs to know what it should do when it wakes up.
So, when the MCU comes out of reset, it reads vector table from flash memory, and loads the two intial entries which are commonly known as first word and second word. First word is a Inital Main stack pointer that gets loaded into the Main Stack Pointer Register(MSP), and the second word is the address of Reset Handler thatis loaded into the Program counter.
Now, you might be wondering why we need Main stack pointer, and Address of Reset Handler.
Main Stack Pointer is loaded because CPU needs to know valid stack before executing the program. Also, if you didn't know stack is temporary workspace for execution. The reset handler is loaded into PC and it will automatically get executed here is where we will get control and write our startup code.
Now we will start wirting code.
Start by creating startup.c, and define the vector table and functions. Here is the code snippet.
#include <stdint.h>
__attribute__((noreturn)) void Reset_Handler(void)
{
while (1)
{
}
}
extern uintptr_t _estack;
__attribute__((noreturn)) void NMI_Handler(void)
{
while (1)
{
}
}
__attribute__((noreturn)) void HardFault_Handler()
{
while (1)
{
}
}
const uintptr_t vector_table[] __attribute__((section(".isr_vector"))) = {
(uintptr_t)&_estack,
(uintptr_t)Reset_Handler,
(uintptr_t)NMI_Handler,
(uintptr_t)HardFault_Handler
}; Let's understand what we written.