Try Embedded

Boot, vector table and clock bring-up

Reset sources, the vector table and bringing up the clock tree.

The first microseconds

From power-on to your first line of main, a microcontroller goes through a fixed sequence. When a board "does nothing", the fault is almost always in this sequence, so it pays to know each step.

  1. Power-on reset. The supply rises; a power-on-reset (POR) and brown-out (BOR) circuit holds the core in reset until the voltage is stable.
  2. Boot mode selection. Boot pins or option bytes choose what is mapped at address 0: user flash, system memory (the factory ROM bootloader) or SRAM.
  3. Vector fetch. The core reads the initial stack pointer from offset 0 and the reset handler address from offset 4.
  4. Reset handler. Runs on the internal RC oscillator (for example 16 MHz HSI on STM32F4): copies .data, zeroes .bss, calls SystemInit.
  5. Clock bring-up. Usually in SystemInit or early in main: start the crystal, configure the PLL, set flash wait states, switch the system clock.
  6. main.

Reset sources

Most MCUs record why they reset in a status register (RCC_CSR on STM32, RSTCAUSE on others). Read it early, save it, then clear the flags, because they are sticky across resets.

FlagCauseWhat it suggests
POR / BORPower-on or supply dipNormal start, or a weak supply
PINExternal reset pinButton, debugger, or a supervisor chip
SFTSoftware reset (NVIC_SystemReset)Intentional: after an update or a fatal error
IWDG / WWDGWatchdogThe firmware hung or a task overran
LPWRIllegal low-power entryConfiguration bug

Logging the reset cause at every boot is one of the cheapest diagnostics you can add to a product.

#include <stdio.h>
#include <stdint.h>

#define RCC_CSR (*(volatile uint32_t *)0x40023874u)
#define CSR_RMVF    (1u << 24)
#define CSR_PINRSTF (1u << 26)
#define CSR_PORRSTF (1u << 27)
#define CSR_SFTRSTF (1u << 28)
#define CSR_IWDGRSTF (1u << 29)

static const char *reset_cause(uint32_t csr) {
  if (csr & CSR_IWDGRSTF) return "independent watchdog";
  if (csr & CSR_SFTRSTF)  return "software reset";
  if (csr & CSR_PORRSTF)  return "power-on";
  if (csr & CSR_PINRSTF)  return "reset pin";
  return "unknown";
}

int main(void) {
  RCC_CSR = CSR_IWDGRSTF | CSR_PINRSTF;     /* pretend the hardware latched these */
  uint32_t csr = RCC_CSR;                   /* read once, early */
  RCC_CSR |= CSR_RMVF;                      /* on real hardware this clears the flags */
  printf("last reset: %s (CSR = 0x%08X)\n", reset_cause(csr), csr);
  return 0;
}

The watchdog flag is checked first because a watchdog reset also asserts the pin-reset flag on many parts (the reset is driven out through the pin).

The vector table

The vector table is an array of addresses at the start of flash: first the initial stack pointer, then the reset handler, then the system exceptions (NMI, HardFault, MemManage, BusFault, UsageFault, SVCall, PendSV, SysTick), then one entry per peripheral interrupt.

__attribute__((section(".isr_vector"), used))
const void *const vector_table[] = {
  &_estack,              /* 0x00 initial SP */
  Reset_Handler,         /* 0x04 */
  NMI_Handler,           /* 0x08 */
  HardFault_Handler,     /* 0x0C */
  /* ... system exceptions ... */
  WWDG_IRQHandler,       /* 0x40: IRQ 0 */
  /* ... one per interrupt ... */
};

Unused entries point to a Default_Handler that loops forever, usually defined as a weak alias so your own handler with the same name overrides it. If a peripheral interrupt fires and you see the CPU stuck in Default_Handler, the handler name is misspelt or missing extern "C" in C++.

On Cortex-M3 and above, SCB->VTOR moves the table, which bootloaders rely on (the application has its own table at its own address).

The clock tree

Clocks have several possible sources and a tree of dividers that feed the core, the buses and each peripheral.

SourceTypicalAccuracyNotes
Internal RC (HSI)8 to 16 MHz±1%Available immediately after reset
External crystal (HSE)8 to 25 MHz±20 ppmNeeded for USB, CAN, accurate UART
PLLMultiplies HSI or HSEInherits sourceProduces the high core clock
Low-speed crystal (LSE)32.768 kHz±20 ppmReal-time clock
Low-speed RC (LSI)~32 kHz±several %Independent watchdog

A typical bring-up on a part with flash wait states:

  1. Enable the HSE and wait for its ready flag (with a timeout, falling back to HSI if the crystal fails).
  2. Configure the PLL: input divider, multiplier, output divider. Enable it and wait for lock.
  3. Increase the flash wait states first. Flash cannot keep up with a fast core; running at 168 MHz with 0 wait states reads garbage instructions.
  4. Set the bus prescalers so each bus stays within its maximum frequency.
  5. Switch the system clock to the PLL and wait until the switch is confirmed.
  6. Update the stored core frequency (SystemCoreClock) so SysTick and baud-rate calculations are right.

When lowering the frequency, do it in the opposite order: switch the clock down, then reduce the wait states.

Pitfall: Every peripheral clock is off after reset. Writing to a peripheral's registers before enabling its clock in the RCC (or equivalent) is silently ignored. "My GPIO writes do nothing" is usually this.

Debugging a board that does not boot

  • Check the boot pins: is the part booting from the ROM bootloader instead of flash?
  • Halt with a debugger and look at the PC. Stuck in Default_Handler or HardFault_Handler? Waiting forever on a "HSE ready" flag with no crystal fitted?
  • Read the reset-cause register to see whether it is resetting repeatedly.
  • Check the vector table is at the address the core expects (and that KEEP kept it).

Interview question: Describe the boot sequence of a Cortex-M microcontroller.

Answer: The power-on reset circuit releases the core once the supply is stable. Boot pins or option bytes decide what is aliased at address 0. The core loads the main stack pointer from the first word of the vector table and jumps to the reset handler from the second. The reset handler, still running on the internal RC oscillator, copies .data, zeroes .bss and calls SystemInit, which sets up the clocks (crystal, PLL, flash wait states, bus prescalers), possibly the FPU and VTOR. Static constructors run, then main.

Interview question: Why log the reset cause at boot, and how?

Answer: It tells you whether the device restarted because of power-on, a brown-out, a watchdog, a software reset or the reset pin, which is essential for diagnosing field failures such as hangs or a weak supply. Read the reset status register as the first thing in main (or before clearing it in startup), store the value, clear the sticky flags so the next reset is reported correctly, and log or count it, ideally alongside a crash record kept in a no-init RAM section.

Build it: set the clocks before anything else

This is step 4, the last of the module project. The meter's chip boots on its slow internal oscillator. Early in startup, the firmware switches to the precise external crystal and multiplies it with the PLL up to full speed, and the flash needs extra wait states first, or the CPU reads garbage from it. Work out the PLL settings and the wait states for any target speed.

Lab: PLL settings and flash wait states

The crystal (HSE) is HSE_HZ, 8 MHz. The PLL, as on an STM32F4:

  • divide by M (2 to 63) to get the VCO input, which must be 1 to 2 MHz; use 2 MHz (less jitter);
  • multiply by N (50 to 432) to get the VCO output, which must be 100 to 432 MHz;
  • divide by P, one of 2, 4, 6, 8, to get the system clock (SYSCLK).

pll_config(target_hz, cfg) finds settings giving exactly target_hz: with M fixed for a 2 MHz input, try P = 2, 4, 6, 8 in order and take the first whose N is a whole number in range with the VCO in range. It returns true and fills cfg, or returns false if no setting gives exactly the target, or the target is above SYSCLK_MAX (168 MHz).

flash_wait_states(hclk_hz) returns the wait states at 3.3 V: 0 up to 30 MHz, 1 up to 60 MHz, 2 up to 90 MHz, and so on (one more for every 30 MHz, a boundary value belonging to the lower band).

Going deeper

Interview question: How would you get a car's rear-view camera on screen within two seconds of starting?

Answer: Measure the boot time from power to first frame and attack the biggest pieces: a minimal bootloader, clocks and DRAM configured early, the camera path started before the rest of the system, decompression or loading that runs in parallel, and work deferred until after the first frame. Regulations set the deadline, so it is tested on every build.

Interview question: What is the clock security system and why enable it?

Answer: On STM32 and similar parts, the clock security system monitors the external crystal oscillator. If the crystal fails, it switches the system clock to the internal RC oscillator and raises a non-maskable interrupt, so the device keeps running and firmware can react, for example by entering a safe state or reporting a fault, instead of hanging. Without it, a broken crystal stops the system.

Interview question: Why does SystemCoreClock need updating after changing clocks?

Answer: Libraries and drivers use that variable to compute SysTick reload values, UART baud-rate divisors and delays. If the clock tree changes and the variable is not updated (SystemCoreClockUpdate in CMSIS), every derived timing is wrong: delays are too long or short and serial ports run at the wrong baud rate.

Explain it: In your own words, explain the order of steps to raise a microcontroller's clock from its internal oscillator to a fast PLL clock.

Answer: Start the external crystal and wait, with a timeout, until it reports ready. Configure the PLL's dividers and multiplier from that source and wait for it to lock. Before switching, increase the flash wait states so flash can keep up with the faster core, and set the bus prescalers so each bus stays within its maximum frequency. Then switch the system clock to the PLL, wait until the switch is confirmed, and update the stored core clock value used for timing calculations.