First Light

Your board is powered and your code compiles, yet the LED stays dark. Four hidden gates stand between main() and the light: a clock, a pin mode, a mux and a PLL.

Learn what a microcontroller looks like at reset, which registers you must write, in which order, and how to find the one that you missed.

The board below starts broken, like a real one on day one. Flip the switches until PA5 blinks. Watch which stage turns red and read why. Then we build every gate, piece by piece, from the first volt.

You need a little C and the idea that a register is a named memory address (Core 01 teaches it). We build the rest from zero.

Part of the series Firmware from Zero to Expertise. Facts come from ST’s STM32F401 documents, the RM0368 reference manual and the ST CMSIS and HAL source on GitHub. Full list in the Field Guide. The board below is a model, not real silicon.

Make PA5 blink

A model of an STM32F401 Nucleo (LED LD2 on PA5, high level lights it). The register names, reset values and the 84 MHz limit come from RM0368. Real chips may fail in other ways than the ones drawn here. AF1 and AF5 stand for the timer and SPI1 groups of the F4 family.

Chapter 0

The Blink That Does Not Blink

See why a program that compiles, flashes and runs can still leave one small LED dark

You unbox a new Nucleo board, ST’s low-cost development board with an STM32F401RE chip on it. You write the oldest program in embedded work: turn the green LED on, wait, turn it off, wait, repeat. The build has no errors. The flash tool says “verified”. You press reset, and nothing happens.

The chip is not broken. The program is not wrong in the way a compiler can see. The CPU is running your instructions right now, one after another, at 16 million per second. The light is dark because your instructions reach nowhere.

A chip that wakes up with everything switched off

Think of a hotel at night. The building has power, but every room is dark and every door is locked. A guest has to ask the front desk to unlock a door and switch on the light before anything else works. This is how a microcontroller (a single chip that holds a CPU, memory and many small hardware blocks called peripherals) wakes up.

RM0368, the reference manual for this chip, says it plainly: “After each device reset, all peripheral clocks are disabled (except for the SRAM and flash memory interface).” A clock is a steady stream of pulses that makes a hardware block do work. No clock means no work, and it also means almost no power. The chip starts quiet on purpose.

So between your main() and the light there is a short chain of gates. Each one is closed at reset. Each one has its own register, and each one fails in its own way.

  1. The clock gate. The block that holds the pin registers, called GPIOA, has no clock. Writes to it do nothing.
  2. The pin mode. A pin can be an input, an output, hooked to a peripheral, or analog. At reset it is an input.
  3. The pin mux. A mux (short for multiplexer) is a selector that lets one pin serve many functions. If it points at the wrong function, your output bit is ignored.
  4. The clock tree. The speed of the whole chip comes from a tree of oscillators, dividers and a PLL (a circuit that multiplies a slow clock into a fast one). A wrong setting can hang the chip or make your delay the wrong length.

There is a fifth trap that is not hardware. Your compiler may delete the delay loop that makes the blink slow enough to see. Chapter 8 covers it.

Try the four gates one at a time

Here is a game. Each puzzle shows a board whose LED is dark or wrong, with a few facts a debugger would give you. Pick the gate that is the cause. The chain turns red at the stage that blocks the signal.

Find the closed gate

Read the symptom, then choose the gate you suspect. The chain shows what the board is really doing. Four boards, one gate each.

A model of the STM32F401 Nucleo, not real silicon. The register values shown are what a debugger would read from the model. RM0368 gives the reset values and the 84 MHz limit.

Notice what the four puzzles share. In none of them is the C code wrong in the way a compiler can see. Each fault is a missing step in a conversation with the hardware, and the chip stays polite and silent about it. There is no error message. This silence is the main difficulty of firmware.

Why this blink matters more than it looks

Every peripheral you will ever use on this chip needs the same steps. A serial port needs its clock enabled, its pins muxed and the chip clock fast enough for the baud rate you want. An ADC needs the same. The blink is the smallest complete example of all of them, and it needs only one LED to check.

This lesson uses one exact part, the STM32F401RE (a Cortex-M4 core, up to 84 MHz), on a Nucleo-64 board, because exact numbers are what let you debug. The ideas carry over to every other chip. Only the register names change. The last chapter gives a table for how the same four gates look on an nRF52840 and an RP2040.

The road

  1. What the chip looks like at reset: the exact bits the manual promises before your first line runs.
  2. The clock gate: enable GPIOA, and why a write to a gated block is lost.
  3. The pin cell: mode, type, speed, pull, output data, and the register that sets one bit safely.
  4. The pin mux: alternate functions, and the debug pins you must not steal.
  5. Clock sources and the PLL: from 16 MHz to 84 MHz, with every limit checked.
  6. Switching safely: wait states, prescalers and the order of seven steps.
  7. Frequency and power: what each gate and each megahertz costs.
  8. The blink itself: delay loops, the compiler and SysTick.
  9. A bring-up method: measure first, guess never.
  10. The field guide: numbers, checklist and code on one page.
Your blink program runs but the LED is dark. A debugger read shows RCC_AHB1ENR = 0x00000000. What does that tell you?

Chapter 1

What the Chip Looks Like Before Your First Line

Read the reset values the manual promises, and learn which clock and which pins you start with

Power arrives. The supply rises past the reset threshold. For a few microseconds nothing runs, then the CPU wakes up and fetches its first instruction. At that moment, before any code of yours, what is true?

You need to know this exactly. A bring-up bug is almost always a wrong belief about the starting state. The belief “the pin is an output” or “the clock is fast” feels harmless until the LED stays dark. So we read the starting state from the manual, not from memory.

Registers have reset values

A register is a small memory cell with a fixed address that controls hardware (Core 01 covers the idea). Each register has a reset value: the number the hardware forces into it when the chip resets. The reference manual lists it for every register. When you open a register in the manual, read its reset value first.

The reset path in the vector table lesson shows how the CPU gets to main(). This chapter covers what the hardware around the CPU looks like when it arrives there.

The clock after reset: HSI, 16 MHz

The chip needs a clock before it can run any code. At reset it uses the HSI, the high speed internal oscillator. It is a small circuit inside the chip that makes 16 MHz without any outside part. RM0368 says each device is “factory calibrated by ST for 1% accuracy” at 25 degrees Celsius. The ST HAL header agrees with the speed: HSI_VALUE is 16000000.

Think of a kitchen clock with no connection to the radio. It runs well, and it drifts a little with the weather. A crystal (the HSE, high speed external oscillator) is the radio-controlled clock: more exact, but it needs a part on the board and a few milliseconds to start. For a blink, 1% is plenty.

The register that holds the oscillator switches is RCC_CR at offset 0x00 of the RCC block (the Reset and Clock Control block, base address 0x40023800). Its reset value is 0x0000XX81, where the X digits are factory calibration that differs per chip. Take the low byte 0x81 apart:

0x81 = 1000 0001 in binary. Bit 0 = 1 (HSION, the HSI is on). Bit 7 = 1 (part of the HSI trim value). The ready flag HSIRDY is bit 1.

So after reset the HSI is on and stable, and everything runs from it. The PLL is off. No peripheral clock is on.

The pins after reset

RM0368 says: “During and just after reset, the alternate functions are not active and the I/O ports are configured in input floating mode.” A floating input is a pin that listens and has no pull to a voltage. It drives nothing. It is the safest state, because a pin that drives nothing cannot fight a wire on your board.

There is one exception that matters on day one: the debug pins. The manual lists them: PA15 is JTDI with a pull-up, PA14 is JTCK/SWCLK with a pull-down, PA13 is JTMS/SWDAT with a pull-up. These pins belong to the debug port at reset. The port A mode register shows it:

GPIOA_MODER reset = 0xA8000000 = 1010 1000 0000 ... 0000. Pins 15, 14 and 13 each read 10, which means alternate function. All other pins read 00, which means input.

Remember this. Your debugger talks through PA13 and PA14. In Chapter 3 you will see how one careless write destroys that link.

The pull resistors give the same story. GPIOA_PUPDR resets to 0x64000000, which is 01 for PA15 (pull-up), 10 for PA14 (pull-down) and 01 for PA13 (pull-up). The output speed register GPIOA_OSPEEDR resets to 0x0C000000, which sets PA13 to very high speed. Port A is the special case. Most other ports reset to all zeros. Port B differs because of its own debug pins (MODER 0x00000280).

Read the registers yourself

Below is a register you can edit by hand. Pick a register, then tap a bit to flip it. The read-out decodes the value the way the manual does. Press Reset value to return to the power-on state. Look for the reset values above.

Flip the bits of a register

Tap a bit cell to flip it. Blue cells are bits the manual names. Dim cells are not used in the decode. Try RCC_AHB1ENR bit 0, then GPIOA_MODER bits 11 and 10.

Reset values and the bit positions are from RM0368 and the ST CMSIS header for the F401. The init values (AHB1ENR = 1, MODER = 0xA8000400) are what the blink code of Chapter 2 and 3 writes. The PLL clock source and PLLQ fields are shown for completeness.

Two readings stand out. First, RCC_AHB1ENR resets to 0x00000000, so every gate is closed. Second, the port A mode register has only three pins configured, and all of them belong to the debugger. Nothing you want is on yet.

What this means for the first line of main()

Write down your starting beliefs as a short list. Check each against the manual before you code.

  1. The CPU runs from the HSI at 16 MHz. The PLL is off.
  2. Every peripheral clock is off, except the SRAM and the flash interface.
  3. Every pin is a floating input, except PA13, PA14, PA15 (and PB3, PB4), which belong to the debug port.
  4. Writing a peripheral register before its clock is on is not defined by the manual.

Item 4 sets the next chapter. The manual says to enable the clock first, and says nothing about what a premature write does. On real F4 parts it is normally ignored silently. We treat that as the model’s behaviour, and Chapter 2 tests it.

A freshly reset STM32F401 runs your first instruction. Which statement is true?

Chapter 2

The Clock Gate: Switch On a Block Before You Talk to It

Enable the GPIOA clock, see why an early write vanishes, and learn the one-line delay that ST’s own library adds

Imagine you write a value into a register and read it straight back. You expect the same value. You get zero. You write again, harder, in a loop. Still zero. The register is not broken. The block that owns it is asleep.

Every peripheral on this chip receives its clock through a gate. A clock gate is a switch on the clock wire: when it is closed to the block, the block sees no pulses, so its registers cannot capture a write. The idea is simple. The chip designer wants most blocks to cost no power until you need them. Gating the clock is the cheapest way to do that.

One bit per block

The gates live in the RCC block. For the F401, GPIOA hangs on a bus called AHB1 (the AHB is the fast bus that carries the CPU’s memory accesses; the slower APB buses hang below it). The enable register for AHB1 is RCC_AHB1ENR. The manual says: “Bit 0 GPIOAEN: IO port A clock enable. Set and cleared by software.” Zero means the clock is disabled and one means enabled. The register resets to zero.

There is one enable register per bus. Blocks on AHB1 use RCC_AHB1ENR (offset 0x30 from the RCC base), slow peripherals use RCC_APB1ENR (0x40) and fast ones use RCC_APB2ENR (0x44). When you add a UART or a timer later, your first question is: which bus, and which bit?

In C, enabling the clock is one line. We write the register address by hand so that nothing is hidden:

c/* addresses from RM0368 table 1 and the ST CMSIS header */
#define RCC_BASE      0x40023800u
#define RCC_AHB1ENR   (*(volatile uint32_t *)(RCC_BASE + 0x30u))
#define GPIOA_BASE    0x40020000u
#define GPIOA_MODER   (*(volatile uint32_t *)(GPIOA_BASE + 0x00u))

RCC_AHB1ENR |= (1u << 0);        /* GPIOAEN: open the clock gate        */
(void)RCC_AHB1ENR;                /* read back: give the gate time to open */
GPIOA_MODER = (GPIOA_MODER & ~(3u << 10)) | (1u << 10);  /* PA5 = output */

Read the first line as: take the old value of the register, set bit 0, and write the result back. Using |= keeps the other gates as they were. Plain = would close every gate you opened earlier.

What a write to a sleeping block does

The manual tells you to enable the clock first: “Before using a peripheral you have to enable its clock in the RCC_AHBxENR or RCC_APBxENR register.” It does not say what a write to a gated block does. The common result on STM32 parts is that the write is silently ignored and a read returns zero. That is the behaviour the model in this lesson uses. Treat it as a field report, not as a promise from the manual.

The lesson for you: a silent failure has no error, no exception and no flag. Your only defence is to know the order, and to read the registers back during bring-up.

The delay after the gate opens

The gate does not open in zero time. ST documents this in its errata sheets for the F4 family under the title “Delay after an RCC peripheral clock enabling”. The listed workarounds include two NOP instructions, one DSB barrier, or “a dummy read operation from the corresponding register just after enabling the peripheral clock” (as quoted by a reader of the F40x errata on ST’s community forum). A forum summary puts the delay at about two bus cycles on AHB. I have not read the F401 erratum text itself, so check your part’s errata sheet.

ST’s own HAL does the same thing. Each clock-enable macro writes the bit, then reads the register back into a temporary variable, under the comment “Delay after an RCC peripheral clock enabling”. The read costs one instruction and removes the risk.

Run the experiment below. The timeline shows what happens on each bus cycle. The CPU enables the clock, optionally reads back, then writes MODER. Try each combination.

Enable, then write

Switch the two options, then press Run the init code. The playhead walks the bus cycles. Purple is the GPIOA clock. Teal arrows are your writes.

Illustrative model: the clock is ready two bus cycles after the enable write, and a MODER write that lands earlier is lost. Real parts differ; ST lists the delay as an erratum and gives no cycle count in the reference manual. Reads of a gated block return zero in the model.

With the read-back on, the write lands after the gate is ready and MODER becomes 0xA8000400. With the clock off, the write bounces and MODER stays at 0xA8000000, the reset value from Chapter 1. With no read-back, the write arrives in the unsafe window.

The same rule for every peripheral

From now on the checklist for any peripheral is the same. Find its bus. Set its enable bit. Read the register back. Only then configure it. A UART, an SPI port and a timer all follow this.

The clock gate is also your first power control. A block with its gate closed uses almost nothing. Chapter 7 puts a number on that saving.

Your init code writes GPIOA_MODER, then sets GPIOAEN in RCC_AHB1ENR. The pin is still an input. Why?

Chapter 3

The Pin Cell: Mode, Type, Pull and One Safe Write

Turn PA5 into an output that can really drive the LED, and learn the one-line bug that locks out your debugger

The clock is on. Now the chip must decide what PA5 is. A pin on the package is just a metal leg. Behind it sits a small circuit, the pin cell, and a handful of registers decide how that circuit behaves. Get one wrong and the LED stays dark even though every other step is right.

Picture the pin as a door with two levers. One lever connects the pin to the 3.3 V supply. The other connects it to ground. A third setting lets go of both levers, and the pin floats. Everything in this chapter is about which lever you pull, and who is allowed to pull it.

Five registers, one pin

Each GPIO port (a GPIO is a general purpose input or output) has a block of registers. The offsets from the port base (GPIOA is 0x40020000) are: MODER at 0x00, OTYPER 0x04, OSPEEDR 0x08, PUPDR 0x0C, IDR 0x10, ODR 0x14, BSRR 0x18 and the alternate function registers at 0x20 and 0x24. They are the same for every port.

  1. MODER (mode): two bits per pin. 00 is input (the reset state), 01 is general purpose output, 10 is alternate function, 11 is analog. PA5 sits at bits 11:10.
  2. OTYPER (output type): one bit per pin. It picks push-pull or open-drain.
  3. OSPEEDR (output speed): two bits per pin, from low to very high. Faster edges look cleaner but radiate more noise. The manual refers you to the datasheet for the actual speeds.
  4. PUPDR (pull-up, pull-down): two bits per pin. It adds a weak resistor to the supply or to ground.
  5. ODR (output data) and IDR (input data): the level you ask for, and the level the pin really has.

Push-pull and open-drain

The manual defines the two output types. In push-pull mode, “a 0 in the output register activates the N-MOS whereas a 1 activates the P-MOS”. The N-MOS is the lever to ground, the P-MOS the lever to supply. The pin is driven hard both ways. In open-drain mode, a 0 activates the N-MOS and a 1 “leaves the port in Hi-Z”: it lets go. The pin can only pull down. A resistor to the supply, outside or inside, pulls it up.

On the Nucleo, LED LD2 is wired from PA5 through a resistor to ground, and a high level lights it (the board manual says that driving the I/O high turns the LED on). Now think about what open-drain does here. A 1 lets go, so nothing pushes current into the LED. A 0 pulls the pin to ground, so the LED has no voltage across it. The LED can never light. The fix is one bit: use push-pull.

Try it. Set the mode to output, then change the type, the pull and the data bit, and read what the pad does.

Drive the pad

The two switches inside the cell are the P-MOS (to 3.3 V) and the N-MOS (to ground). Choose what the registers say, and watch which switch closes.

Illustrative values: a 3.3 V supply, a green LED that drops 2.0 V and a 1 kilohm resistor, so 1.3 mA. The real LD2 resistor is on the board schematic (UM1724). The push-pull and open-drain behaviour is the manual’s. A pull resistor is far too weak to light the LED, so it does not.

With push-pull and ODR = 1, the P-MOS closes, the pad sits at 3.3 V, and 1.3 mA flows through the LED (illustrative). With open-drain and ODR = 1, the pad floats and the LED is dark. That is the whole difference between a working and a dead blink.

Setting one bit without touching the others

To toggle PA5 you must change one bit of ODR and leave the other fifteen alone. The obvious way is GPIOA->ODR |= (1u << 5). It hides three steps: read ODR, set bit 5 in a register copy, write the copy back. If an interrupt changes PA3 between your read and your write, your write erases that change.

main reads ODR = 0x0000. An interrupt sets bit 3: ODR = 0x0008. main writes back 0x0020. Bit 3 is lost.

The manual gives you the cure: “The GPIOx_BSRR register provides a way of performing atomic bitwise handling.” BSRR is a write-only register. Writing a 1 to bit n of the low half sets pin n. Writing a 1 to bit n+16 of the high half resets it. A zero changes nothing. If both are 1 for the same pin, “the set action takes priority”. One store does the job, so no interrupt can fit inside it:

cGPIOA_BSRR = (1u << 5);          /* PA5 high: BS5 is bit 5  (0x00000020) */
GPIOA_BSRR = (1u << (5 + 16));  /* PA5 low:  BR5 is bit 21 (0x00200000) */

The one-line bug that locks you out

Now the trap promised in Chapter 1. A beginner writes GPIOA_MODER = (1u << 10); to make PA5 an output. It works on the first try. It also overwrites the whole register. The reset value 0xA8000000 held the debug pins PA13, PA14 and PA15 in alternate function mode. After the write, MODER is 0x00000400, and those three pins are plain inputs.

The symptom appears at the next download: the debugger says it cannot connect to the target. The measurement is easy to guess once you know the cause: read MODER and see 0x400 where 0xA8000400 should be, or watch the SWCLK pin stay quiet. The fix is to mask: clear only your two bits, then set yours. Chapter 2’s example did it correctly. If you are already locked out, hold the chip in reset while you connect and erase the flash.

PA5 is an output and ODR bit 5 is 1, but the pad stays at 0 V and the LED is dark. The pin is set to open-drain with no pull-up. What is the right reading?

Chapter 4

The Pin Mux: Who Owns the Pad?

Choose which block drives a pin, and see why the right output bit can do nothing at all

The STM32F401RE comes in a package with 64 pins, and about fifty of them are general purpose pins. The chip has far more signals than that: serial ports, SPI buses, timer outputs, an ADC, USB. Where do they all go? They share pins. Each pin can serve several jobs, and you choose one.

Think of an old telephone switchboard. One line comes into the building, but behind it sits a rotary switch that connects it to one of sixteen desks. Only one desk is connected at a time. The others still exist, they just cannot reach the line.

The two-step choice

On the STM32 the rotary switch has two settings that you write.

  1. Hand the pad to the mux. In MODER, the two bits for the pin must read 10, alternate function mode. Without this the pad stays with the GPIO block, whatever the next step says.
  2. Pick the desk. The registers AFRL (pins 0 to 7, offset 0x20) and AFRH (pins 8 to 15, offset 0x24) hold four bits per pin. The value 0 to 15 selects AF0 to AF15.

The manual states the rules: “After reset all I/Os are connected to the system’s alternate function 0 (AF0).” And: “The peripherals’ alternate functions are mapped from AF1 to AF13.” Which peripheral lives on which AF number for which pin is not in the reference manual. It is in the alternate function mapping table of the datasheet, one cell per pin and per AF. Reading that table is a core skill, and the datasheet lesson (Core 00) shows how.

For PA5, the pin on which the Nucleo wires its LED, the F4 family has a timer channel on AF1 (TIM2_CH1) and the SPI1 clock on AF5 (SPI1_SCK). I took this from the family pattern in the F2 and F4 reference manuals; check the F401 datasheet table for your part.

A worked example

Let us hand PA5 to AF1. The steps with every number:

  1. MODER field for PA5 must become 10. Binary 10 at bits 11:10 is 2 << 10 = 0x00000800. The old value was 0xA8000000. Clear bits 11:10 (they were 00), then OR in 0x800. The result is 0xA8000800.
  2. PA5 uses bits 23:20 of AFRL, because pin 5 times 4 bits equals bit 20. AF1 is the value 0001. So AFRL = 1 << 20 = 0x00100000.
  3. The timer must be clocked and counting. This is a separate block with a separate gate (Chapter 2) and is the subject of Core 04.

If you skip step 3, the pad belongs to the timer but the timer is asleep. The pad sits at its idle level. Your ODR writes do nothing, because in alternate function mode the output data register is not connected to the pad.

The failure, as symptom, measurement and fix

Symptom. You set PA5 as an output a minute ago in some other file. The LED never changes, although your code writes ODR in a loop.

Measurement. Read MODER. If bits 11:10 read 10 instead of 01, a library or leftover init code moved the pin to the mux. Read AFRL bits 23:20 to see who owns it.

Fix. Set MODER bits 11:10 back to 01. Or, if you meant to use the peripheral, enable and start it. The same trap appears the other way round: a pin you wanted for SPI stays in general output mode and the SPI clock never appears.

On the Nucleo there is a neighbour effect too. LD2 shares PA5 with the board’s D13 header pin, which Arduino-style shields use as the SPI clock. Start SPI1 on that pin and the LED flickers with every clock edge. The LED is a free logic probe.

The pins you must not steal

Chapter 1 showed three pins in AF mode at reset: PA13, PA14 and PA15. Two of them carry the debugger: SWDIO on PA13 and SWCLK on PA14. If your code turns PA13 into a GPIO output, the debugger loses its data line. The chip keeps running, the LED may even blink, and the next download fails. On most parts the debug pins are marked in the datasheet; keep them as they are unless you really mean to reuse them.

Use the device below. Pick a pin, choose general output or alternate function, and select an AF number with the slider. The panel on the right shows who drives the pad and what you see.

Turn the rotary switch

Choose a pin and a mode. In alternate function mode, move the AF slider and read which block drives the pad. Switch the timer on to see the pin come alive.

AF0

Only the functions named in the text are drawn; other AF numbers have functions on a real chip. AF1 and AF5 for PA5 are the F4 family pattern, and PA13 carries SWDIO at reset (RM0368 lists it as JTMS/SWDAT). The timer toggle stands in for Core 04.

On PA5, AF1 with the timer off gives a steady dark LED. AF1 with the timer on gives a 1 Hz blink without any CPU instruction. That is why peripherals exist: once set up, they work without you.

MODER bits for PA5 read 10 and AFRL selects a timer that is not running. Your code toggles ODR bit 5. What do you see on the pin?

Chapter 5

Clock Sources and the PLL: From 16 to 84 MHz

Choose a source, multiply it with a PLL, and check every limit before the chip locks up

The LED blinks now, slowly, at 16 MHz. The chip can do more. Your next job needs to read a sensor fast, or talk to a USB host, and 16 million cycles per second is not enough. The chip can run up to 84 MHz, which is 5.25 times faster. To get there you must build a faster clock.

You cannot just ask an oscillator inside the chip for 84 MHz. Small, cheap oscillators are not accurate at that speed. The trick is to start from a slow, steady clock and multiply it. The circuit that multiplies is the PLL.

Three clock sources

RM0368 lists them: “Three different clock sources can be used to drive the system clock (SYSCLK)”. They are the HSI oscillator, the HSE oscillator and the main PLL.

How a PLL multiplies, in plain words

Picture a drummer who taps a slow steady beat, and a second player who wants to play 336 times faster. The second player listens to the slow beat and counts his own taps. If he is too slow, he speeds up. If he is too fast, he slows down. When his count lines up with the drummer’s beat, he has locked. The fast player is the VCO, the voltage-controlled oscillator. The counting and correcting is the loop.

The F401 PLL has three dividers and one multiplier. You set them in the register RCC_PLLCFGR, in these fields:

M (PLLM)
Divides the source first. Allowed: 2 to 63. The result, the VCO input, must be 1 to 2 MHz. The manual recommends 2 MHz to limit jitter.
N (PLLN)
Multiplies the VCO input. The manual writes the limit as 192 to 432, so the VCO output lies in 192 to 432 MHz.
P (PLLP)
Divides the VCO output to make SYSCLK. Allowed: 2, 4, 6 or 8. SYSCLK must not exceed 84 MHz.

A second divider, PLLQ, makes the 48 MHz that USB needs from the same VCO: fVCO / Q.

A worked example, every step

Goal: 84 MHz from the HSI. Try M = 16, N = 336, P = 4.

  1. VCO input = 16 MHz / 16 = 1 MHz. This is inside 1 to 2 MHz. Pass.
  2. VCO output = 1 MHz × 336 = 336 MHz. Inside 192 to 432 MHz. N = 336 is also inside 192 to 432. Pass.
  3. SYSCLK = 336 MHz / 4 = 84 MHz. At or below 84 MHz. Pass.
  4. USB clock with Q = 7: 336 / 7 = 48 MHz. Pass, if you need USB.

Now try to be clever and use a 2 MHz VCO input for less jitter: M = 8, then N = 168 would give the same 336 MHz. But the manual’s N range starts at 192, so N = 168 is illegal here. That is why most F401 examples use M = 16 and N = 336 from the HSI.

The failure: the PLL that never locks

Symptom. The program starts, then does nothing. The LED stays dark and the debugger shows the program counter inside a loop.

Measurement. The loop is while (!(RCC->CR & RCC_CR_PLLRDY)). The flag PLLRDY is bit 25 of RCC_CR, and it reads 0. Read RCC_PLLCFGR and decode M, N and P as in Chapter 1. A VCO input outside 1 to 2 MHz is a common cause (say M = 2 with the HSI, so 8 MHz). The manual does not promise a lock outside its limits.

Fix. Choose values that pass every check in the example. Write RCC_PLLCFGR before setting PLLON. The manual says the PLL parameters “cannot be changed once PLL is enabled”.

Use the calculator below. Choose a source, then move the dividers, and watch which stage turns red. The presets show a good value and two bad ones.

Build a clock

Each block shows its frequency and turns red when it breaks a limit from the manual. Read the sentence below for the exact rule.

16
336

Limits are from RM0368: VCO input 1 to 2 MHz, 2 ≤ M ≤ 63, N between 192 and 432, P in {2, 4, 6, 8}, SYSCLK up to 84 MHz. The datasheet also lists the VCO output range; check DS10086 for your part. The HSE value of 8 MHz is an example.

The hero preset gives 84 MHz. Change M to 2 with the HSI and the VCO input reads 8 MHz, four times the allowed 2 MHz, and the block turns red. The chip would hang at the PLLRDY loop on a real board.

The HSI feeds the PLL with M = 16 and N = 336. What are the VCO output and SYSCLK with P = 4?

Chapter 6

Switching Safely: Wait States, Prescalers and the Right Order

Put seven steps in the right order so the chip reaches 84 MHz without crashing on the way

The PLL is configured and legal. You write the switch, and the board resets or freezes. The numbers were right. The order was wrong. At the moment of the switch, something else in the chip could not keep up.

That something is the flash memory. Your program lives there, and the CPU fetches every instruction from it. Flash is slower than a fast CPU clock. When the clock rises, the CPU has less time per fetch. If flash cannot answer in time, the CPU reads the wrong bits.

Wait states: telling the CPU to be patient

A wait state is one extra CPU clock cycle that the CPU waits for the flash to answer. More wait states means a slower fetch per instruction, but a fast clock can use it. The chip needs to know how many to use. You tell it in the register FLASH_ACR (flash base 0x40023C00, offset 0x00), in the field LATENCY at bits 3:0. The manual says: “To correctly read data from flash memory, the number of wait states (LATENCY) must be correctly programmed in the Flash access control register (FLASH_ACR) according to the frequency of the CPU clock (HCLK) and the supply voltage of the device.”

For a supply of 2.7 to 3.6 V, which includes the 3.3 V of a Nucleo, RM0368 Table 6 gives:

HCLK rangeWait statesCPU cycles per flash read
0 to 30 MHz01
30 to 60 MHz12
60 to 84 MHz23

At the reset clock of 16 MHz, zero wait states is right, and FLASH_ACR resets to 0. At 84 MHz you need 2. Lower supply voltages need more wait states at the same speed; the manual has a column for each voltage range. The values above are the 3.3 V column.

The same register holds three speed-up switches: prefetch (bit 8), the instruction cache (bit 9) and the data cache (bit 10). They hide the wait states from most instruction fetches. They are off at reset, and switching them on is a later improvement, not a bring-up need.

Slow buses need a divider

Peripherals do not run on SYSCLK directly. The CPU and memory bus (HCLK) take SYSCLK through the AHB prescaler. The two peripheral buses take HCLK through their own prescalers. The manual limits them: “The maximum allowed frequency of the low-speed APB1 domain is 42 MHz” and the high-speed APB2 domain may reach 84 MHz. So at 84 MHz you must divide APB1 by 2. The field PPRE1 sits at bits 12:10 of RCC_CFGR, and the value 100 means divide by 2.

The seven steps

  1. Set LATENCY to 2 in FLASH_ACR, before the clock gets fast.
  2. Write RCC_PLLCFGR with M = 16, N = 336, P = 4 (the PLL must still be off).
  3. Set the APB1 prescaler to 2 so APB1 never exceeds 42 MHz.
  4. Set PLLON, bit 24 of RCC_CR.
  5. Wait until PLLRDY (bit 25) reads 1.
  6. Write SW = 10 in RCC_CFGR to select the PLL.
  7. Wait until SWS reads 10, which confirms that the switch happened.

The manual covers one more point on step 6: “A switch from one clock source to another occurs only if the target clock source is ready” and “if a clock source that is not yet ready is selected, the switch occurs when the clock source is ready”. So selecting early is not a crash. But your code then believes it runs at 84 MHz while it still runs at 16 MHz, until the PLL locks. Timing loops in that window run too long.

Going back down is the mirror image: switch to the slow clock first, confirm, then lower the wait states.

Now try it. Tap the actions in the order you choose. The chart shows the CPU clock at each step against the clock that the current wait states allow. Red means a fault or a limit broken.

Order the seven steps

Tap each action once, in the order your code would run it. Bars show HCLK after each step. The dashed line is the most the current wait states can support.

A model. Wait-state ceilings are the 2.7 to 3.6 V column of RM0368 Table 6 (read from a converted copy; check the original). The PLL becomes ready one step after PLLON. The reset PLLCFGR (M 16, N 192, P 2 from the HSI) would give 96 MHz, above the 84 MHz limit. Real failures can look different.

The safe order has the wait states first and the switch late. Try putting the switch before the LATENCY write: the clock reaches 84 MHz while the ceiling is still 30 MHz, and the bar turns red.

Which order avoids reading flash too fast on the way to 84 MHz at 3.3 V?

Chapter 7

Frequency, Power and the Gating Budget

Explore the clock tree, open and close gates, and see what each megahertz and each peripheral costs in milliamps

Your blink works at 84 MHz. Now imagine the same code on a coin cell in a sensor that must run for a year. The CPU does almost nothing, yet the battery drains. Where does the current go?

Most of it goes into switching. A digital chip is a very large number of tiny switches. Each time a clock pulse arrives, some of these switches change state, and each change moves a little electric charge. More pulses per second means more charge per second, which is more current.

Dynamic power in one line

The textbook model of a CMOS chip says the dynamic power (the power spent on switching) is proportional to the clock frequency and to the square of the supply voltage:

Pdyn
The power spent on switching, in watts.
α
The share of switches that change on an average clock pulse. A block with a closed clock gate has α = 0.
C
The total capacitance that the clock charges. More active blocks means more C.
V
The supply voltage. It is squared, so a small cut in voltage saves a lot.
f
The clock frequency. Halve it and the dynamic power halves.

Two knobs follow at once. Lower f and the whole chip uses less. Close a clock gate and that block’s share drops to nearly zero. Chapter 2’s gate is a power switch as well as a wiring step.

A second part, the static power, flows even when nothing switches. It comes from leakage and from the voltage regulator. It does not depend on the clock. We keep a small constant for it.

One real anchor

The F401 datasheet gives measured run-mode currents. A copy of the STM32F401 datasheet lists a typical 23.2 mA at 84 MHz, 25 degrees Celsius, with all peripherals enabled and code running from flash with the ART accelerator on. I read it on a datasheet mirror, not on the ST original, so confirm it in DS10086 before you design with it. The datasheet also says these runs use a reduced code that gives a consumption equivalent to CoreMark.

Our explorer below is calibrated to that one number. The split between the core and each peripheral is illustrative: real parts differ, and only the sum is anchored.

Walk the clock tree

Choose SYSCLK, then open or close the peripheral gates. Each branch shows its frequency. The bar shows the modelled current.

Illustrative model: I = 1.0 mA static + (f / 84 MHz) × (14.4 mA core + gate shares of 0.8, 1.8, 1.9, 1.6 and 1.7 mA), so everything on at 84 MHz sums to the 23.2 mA run figure from a datasheet mirror. The energy line assumes 3.3 V and one million cycles of work.

Fast and done, or slow and steady?

Look at the energy line in the read-out. For a fixed job of one million cycles, energy is current times voltage times time. At a lower clock the current drops, but the job takes longer, so the static current is paid for longer. With a static part the energy per job is often lower at the high clock, provided the chip then goes to sleep. This is called race to idle: finish quickly, then sleep. It is not always true, so you measure it. The sleep lesson (pai-fw-07) builds the full battery budget.

Here is the worked example from the model, with every step. At 16 MHz with all five gates open: current = 1.0 + (16 / 84) × (14.4 + 7.8) = 1.0 + 4.23 = 5.23 mA. One million cycles take 1,000,000 / 16,000,000 = 62.5 ms. Energy = 3.3 V × 5.23 mA × 62.5 ms = 1.08 mJ. At 84 MHz: current = 23.2 mA, time = 11.9 ms, energy = 3.3 × 23.2 × 11.9 = 0.91 mJ. The fast run costs less energy for this job, because the static 1.0 mA is paid for a shorter time. The numbers are illustrative; the pattern is why real designs measure.

The failure, as symptom, measurement and fix. The symptom: a device that should last a month on its battery dies in three days. The measurement: put a current meter on the supply, then read RCC_AHB1ENR, RCC_APB1ENR and RCC_APB2ENR in the debugger and count the set bits. A bring-up habit of enabling everything leaves most of them set. The fix: enable only the gates you use, and clear the bit of a block when you finish with it.

The blink at 84 MHz with only GPIOA open shows the lesson: the LED needs one gate and almost no CPU speed. A typical bring-up opens every gate for convenience and forgets to close them later. The measurement that catches this is the current of the whole board.

A block you never use has its clock gate open and the chip runs at 84 MHz. What is the cheapest fix for the wasted current?

Chapter 8

The Blink Itself: Delay Loops, the Compiler and SysTick

Make the LED toggle at a speed your eye can see, and learn why the same loop behaves differently in two builds

Every gate is open. PA5 is an output. The clock is fast. You write the loop that every tutorial shows, build it in debug mode, and the LED blinks. You switch to a release build to save space. Now the LED glows a steady, dim light. Nothing in the source changed.

The cause is not hardware. It is the third kind of gate, the one in your compiler. Remember the question this chapter answers: how does a program wait for half a second?

The delay loop, and how the compiler removes it

The classic wait is a loop that counts and does nothing:

cfor (uint32_t i = 0; i < N; i++) { }     /* can be deleted by the compiler */
for (volatile uint32_t i = 0; i < N; i++) { }   /* kept: every access is real */

The compiler follows an as-if rule: it may change your program in any way, as long as the visible results stay the same. The visible results of the first loop are none. It writes to no pin, no memory, nothing a later line reads. So at optimisation level -O1 or higher, GCC can delete it. The delay becomes zero cycles, and PA5 toggles as fast as the CPU can write the pin.

The word volatile tells the compiler that every read and write of i is itself visible (an access to hardware, say). It must perform all of them, in order. The loop stays, and it takes time. The vector table lesson explains volatile in depth.

Symptom, measurement, fix. Symptom: the LED looks dim and steady in the release build and blinks in the debug build. Measurement: a scope on PA5 shows a square wave of millions of edges per second, or the disassembly shows no loop. Fix: make the counter volatile, or better, stop using loops for time, as the next section shows.

How long does a loop take?

The loop length in time is its iteration count times the cycles per iteration, divided by the clock. A volatile loop loads and stores the counter every pass, so a pass may take several cycles. Say 4 cycles (illustrative; measure your own). To wait 0.5 s at the reset clock of 16 MHz:

N = 0.5 s × 16,000,000 cycles per s / 4 cycles per pass = 2,000,000 passes.

Now raise the clock to 84 MHz and keep N. One half-period becomes 2,000,000 × 4 / 84,000,000 = 95.2 ms. The blink runs 5.25 times faster, at 5.25 Hz instead of 1 Hz. The delay depends on the clock, on the compiler flags, on flash wait states, and on any interrupt that steals cycles. Every one of these changes the blink without any warning.

A delay loop has a second weakness: it burns the CPU. While it counts, the CPU can do nothing else. A real device must read sensors and answer a host while the LED blinks. A hardware timer (the subject of Core 04) keeps time on its own and leaves the CPU free. For first light, a volatile loop is fine. For anything that stays in the product, use a timer.

Seeing it: what the eye does

Your eye blends fast flashes. Above roughly 50 to 100 Hz a flickering LED looks steady. With a 50 percent duty cycle it looks about half as bright. So a pin that toggles millions of times a second produces a dim, steady glow. That is exactly what you see in the failed release build. The numbers here are approximate and depend on the person.

Time the blink

Pick a way to wait and a clock. The scope shows four seconds of PA5. Turn the optimiser off and on with an empty loop and watch the trace change.

Illustrative model: 4 cycles per volatile pass with N = 2,000,000 (tuned for 1 Hz at 16 MHz), and an unoptimised empty loop costing about the same. A removed loop toggles roughly every few cycles. The SysTick reload is recomputed from the clock, so the rate does not move.

The better way: SysTick

The Cortex-M core has its own small timer called SysTick. It is a 24-bit counter that counts down from a reload value. The reload range is 1 to 0xFFFFFF (16,777,215), according to the cortex-m crate documentation. Bit 2 of its control register (CLKSOURCE) selects the core clock when set. At the end of each countdown it sets a flag or raises an interrupt. Because you compute the reload from the clock, the period stays fixed when the clock changes:

c#define F_CPU  84000000u
SysTick->LOAD = F_CPU / 1000u - 1u;    /* 83,999: one tick per 1 ms           */
SysTick->VAL  = 0u;
SysTick->CTRL = 7u;      /* ENABLE (bit 0) + TICKINT (bit 1) + core clock (bit 2) */
volatile uint32_t ms;
void SysTick_Handler(void) { ms++; }

Two limits follow from the 24 bits. At 84 MHz the longest single countdown is 16,777,216 / 84,000,000 = 0.1997 s. For 500 ms you count several ticks in the handler, as above. The value 7 sets ENABLE (bit 0), TICKINT (bit 1, which raises the interrupt) and CLKSOURCE (bit 2). A version without interrupts can poll the COUNTFLAG bit instead. The handler and its priority are the subject of the interrupts lesson (pai-fw-02).

An empty for loop gives a 1 Hz blink at -O0 and a dim steady glow at -O2. What is the most likely cause?

Chapter 9

A Bring-Up Method: Measure First, Guess Never

Find a dead LED in two or three probes by splitting the signal chain in half, and keep a log as you go

The LED is dark. You have a list of seven things that might be wrong from the last eight chapters. You could change them all at once and hope. Do not. If the LED then works, you do not know which change did it. If it still fails, you do not know which change hid the real bug.

Bring-up is the work of getting a new board or a new chip block to do its first useful thing. It is detective work. The method is old and plain: gather facts, split the problem in half, change one thing, write down what happened.

The ladder: from power to pixel

Work from the bottom of the chain up. Each rung needs the one below it. A fact at rung 5 means nothing if rung 2 is broken.

  1. Power. Measure the supply pin with a multimeter. Expect close to 3.3 V on a Nucleo. A chip without power fails in ways that look like firmware bugs.
  2. The debug link. Does the debugger connect and read the chip? If not, suspect PA13 and PA14 (Chapter 4), the reset line, or the boot pins.
  3. Is code running? Halt the CPU. Does the program counter lie in your code, and where?
  4. The clock. Read RCC_CR and the status field SWS in RCC_CFGR. Which source drives SYSCLK? Is the PLL ready?
  5. The gate. Read RCC_AHB1ENR. Is bit 0 set?
  6. The pin. Read GPIOA_MODER bits 11:10, then AFRL bits 23:20 if the mode is 10.
  7. The signal. Scope the pad. A flat line, a fast hash, or a slow square wave each point to a different cause.
  8. The load. Check the LED polarity and the resistor on the schematic.

With a debugger attached, a register read costs one command, for example x/wx 0x40023830 in GDB reads RCC_AHB1ENR. It is the cheapest measurement you have. Prefer it to editing code.

Split the chain in half

Think of the chain from your code to the LED: code, clock gate, GPIOA registers, mux, pad, LED. Six links. A good first probe checks the middle of the chain. If the pad shows a clean 3.3 V and 0 V square wave, the first five links all work, and the fault is in the LED or in the wiring. If the pad is flat, the fault lies upstream, and one more probe halves it again. Three probes find one fault among eight.

This is a binary search, the same idea as looking up a word in a dictionary. It beats checking links in order whenever the chain is long.

The detective game

The board below has one hidden fault. Probe it and read the facts. Each probe costs one point. Name the fault when you are sure. A good detective needs two or three probes. The button New board picks another fault.

Find the fault

Press a probe to read a fact from the model. The chain shows what the probes have shown. Then pick your diagnosis.

A model of the Nucleo-F401RE. The register values and symptoms follow RM0368 and the earlier chapters. The faults are illustrative and chosen at random from six; a real board may have two at once.

Here is a worked path, every step. The board has a closed GPIOA gate, but you do not know that.

  1. Probe 1: scope PA5. It is flat at 0 V. The pad is dead, so the fault lies in the half of the chain before the pad. Four links remain: code, gate, registers, mux.
  2. Probe 2: read GPIOA_MODER. It reads 0xA8000000, so PA5 bits 11:10 are 00, an input. Either your write never happened, or it was lost. This points at the gate or at the code.
  3. Probe 3: read RCC_AHB1ENR. It reads 0x00000000. GPIOAEN is clear. That is the fault. Three probes, one cause.

Real boards often have two faults at once. After you fix the first, the LED may still be dark, and the chain moves on to the next red link. Do not feel cheated. Repeat the ladder. Each fix removes one cause and shows the next one clearly.

Keep a log

Write each probe and its result in a file. Write each change you make and its effect. A short log such as “RCC_AHB1ENR = 0, set bit 0, LED still dark, MODER = 0xA8000000” saves hours when you return to the bug the next morning. The log also tells a colleague what you already tried.

When the LED finally blinks, do not move on yet. Change one working thing back to broken, and check that the LED fails the way you expect. Now you know why it works.

Your LED is dark. A scope on PA5 shows a clean square wave from 0 V to 3.3 V at 1 Hz. Where is the fault?

Chapter 10

The Field Guide

Keep the numbers, the checklist and the working code for first light on one page

A blink needs four gates in the right state and one honest delay. The clock gate lets writes reach GPIOA. The pin mode and the mux give the pad to the GPIO block. The clock tree sets the speed and must change in a safe order. The delay must not depend on luck. When it fails, you measure the chain in halves and never guess.

The numbers (STM32F401RE)

ItemValueSource
HSI16 MHz, 1% at 25 °C, on after resetRM0368 6.2; HAL HSI_VALUE
RCC_CR reset0x0000XX81 (HSION 0, HSIRDY 1, HSEON 16, HSERDY 17, PLLON 24, PLLRDY 25)RM0368 6.3; CMSIS header
RCC base, AHB1ENR0x40023800; AHB1ENR at +0x30, reset 0; GPIOAEN bit 0RM0368 Table 1, 6.3
GPIOA base0x40020000; MODER +0x00, OTYPER +0x04, OSPEEDR +0x08, PUPDR +0x0C, IDR +0x10, ODR +0x14, BSRR +0x18, AFRL +0x20, AFRH +0x24CMSIS header
GPIOA reset valuesMODER 0xA8000000, PUPDR 0x64000000, OSPEEDR 0x0C000000RM0368 8.4
PA5 fieldsMODER bits 11:10, AFRL bits 23:20, BSRR BS5 bit 5, BR5 bit 21CMSIS header
RCC_PLLCFGR+0x04, reset 0x24003010; PLLM bit 0, PLLN bit 6, PLLP bit 16, PLLSRC bit 22RM0368; CMSIS header
PLL limitsVCO in 1 to 2 MHz; M 2 to 63; N 192 to 432; P 2, 4, 6, 8; SYSCLK up to 84 MHzRM0368 6.3.2
Bus limitsAPB1 up to 42 MHz, APB2 up to 84 MHzRM0368 6.2
RCC_CFGR fieldsSW bits 1:0 (10 = PLL), SWS bits 3:2, HPRE bit 4, PPRE1 bit 10, PPRE2 bit 13RM0368; CMSIS header
Flash wait statesFLASH_ACR at 0x40023C00, LATENCY bits 3:0. At 2.7 to 3.6 V: 0 up to 30 MHz, 1 up to 60 MHz, 2 up to 84 MHzRM0368 3.4, 3.8
Run current23.2 mA typical, 84 MHz, all peripherals onDatasheet mirror; confirm in DS10086
SysTick reload1 to 0xFFFFFF (24 bits)cortex-m crate docs

The same four gates on other chips

The register names change. The questions do not. Here is how each gate looks on two other parts, from their own manuals.

GateSTM32F401nRF52840RP2040
Clock or reset gateRCC_AHB1ENR bit per block, all off at resetThe GPIO chapter lists no enable bitReset controller holds every peripheral in reset at power-up; software must release it
Pin setupMODER, OTYPER, PUPDRPIN_CNF[n] with DIR, INPUT, PULL, DRIVEFUNCSEL resets to 31 (NULL); F5 selects SIO for CPU control
Atomic set and clearBSRROUTSET and OUTCLRNot checked in this lesson
Clock after resetHSI 16 MHz64 MHz CPU clock; HFXO must run for the radioRing oscillator, typically 6 MHz (4 to 8)
Fast clockPLL to 84 MHzHFCLK 64 MHzUp to 133 MHz clk_sys

The bring-up checklist

  1. Measure the supply. Connect the debugger. Halt and find the program counter.
  2. Set LATENCY for the target clock before you raise it.
  3. Write PLLCFGR, set APB1 /2, set PLLON, wait for PLLRDY, set SW, wait for SWS.
  4. Enable the GPIOA clock. Read the register back.
  5. Set PA5 to output with a mask write, never a plain assignment.
  6. Check the pin type (push-pull) and the mux (not an alternate function).
  7. Use BSRR to set and clear. Do not read-modify-write ODR.
  8. Time with SysTick or a timer. Never trust an empty loop.
  9. If it fails, probe the chain in halves. Log each probe and each change.
  10. Close the gates you do not use.

The core as code

c#include "stm32f4xx.h"        /* used only for SysTick->LOAD, VAL, CTRL */
#define REG(a)       (*(volatile uint32_t *)(a))
#define RCC_CR       REG(0x40023800u)
#define RCC_PLLCFGR  REG(0x40023804u)
#define RCC_CFGR     REG(0x40023808u)
#define RCC_AHB1ENR  REG(0x40023830u)
#define FLASH_ACR    REG(0x40023C00u)
#define GPIOA_MODER  REG(0x40020000u)
#define GPIOA_BSRR   REG(0x40020018u)

static volatile uint32_t ms;
void SysTick_Handler(void) { ms++; }
static void delay_ms(uint32_t d) { uint32_t t = ms; while (ms - t < d) { } }

static void clock_84mhz(void) {
  FLASH_ACR = (FLASH_ACR & ~0xFu) | 2u;                     /* 1. two wait states            */
  RCC_PLLCFGR = (16u << 0) | (336u << 6) | (1u << 16) | (7u << 24);
                                                    /* 2. M=16 N=336 P=4 (01) Q=7, HSI */
  RCC_CFGR = (RCC_CFGR & ~(7u << 10)) | (4u << 10); /* 3. APB1 = HCLK / 2           */
  RCC_CR |= (1u << 24);                              /* 4. PLLON                      */
  while (!(RCC_CR & (1u << 25))) { }                /* 5. PLLRDY                     */
  RCC_CFGR = (RCC_CFGR & ~3u) | 2u;                    /* 6. SW = PLL                   */
  while (((RCC_CFGR >> 2) & 3u) != 2u) { }            /* 7. SWS = PLL                  */
}

int main(void) {
  clock_84mhz();
  SysTick->LOAD = 84000000u / 1000u - 1u;                /* 1 ms tick                     */
  SysTick->VAL = 0u; SysTick->CTRL = 7u;

  RCC_AHB1ENR |= (1u << 0); (void)RCC_AHB1ENR;       /* GPIOAEN, then read back       */
  GPIOA_MODER = (GPIOA_MODER & ~(3u << 10)) | (1u << 10);  /* PA5 output; keep PA13/14/15 */
  for (;;) {
    GPIOA_BSRR = (1u << 5);  delay_ms(500);               /* LED on  */
    GPIOA_BSRR = (1u << 21); delay_ms(500);              /* LED off */
  }
}

Note that this program has no HAL and no startup file in view. A real project still needs the vector table and the startup code from the vector table lesson, and the linker script and flags from Core 02.

Keep going

Sources and credit

The facts in this lesson come from primary sources opened for it:

The series plan names Valvano’s Embedded Systems: Shape the World and Stanford’s CS 107E lab 1 as further reading on GPIO and bare-metal first light. They are good companions. I did not copy from them.

The takeaway. A chip wakes up with its blocks switched off, its pins listening and its clock slow. First light is a conversation with that quiet hardware: open the clock gate, own the pad, raise the clock in a safe order, and keep time with a real timer. When it stays dark, measure the chain in halves.

Now press Present or Teach and explain the first light of a chip from memory: the four gates, the seven clock steps, and the three probes. Then go back to the board at the top, break it in a new way, and say out loud which stage turns red and why.

First Light, Firmware from Zero to Expertise, core 03
STM32F401RE documents · Back to Gleams