Skip to content
systemcoding.dev
Embedded

Enable the HSE oscillator and wait for HSERDY on STM32

Set HSEON in RCC->CR and poll HSERDY with a timeout on STM32F4 before using the crystal, so a missing or dead oscillator fails visibly instead of hanging.

1 min read
Summarize in AI

The external crystal on an STM32 is off at reset and takes time to stabilise after HSEON is set. The hardware tells you when it is usable through HSERDY, and the code should wait for that bit rather than for a fixed delay. A bounded wait matters too: if the crystal is not fitted or the load capacitors are wrong, HSERDY never sets.

clock.cc
#include "stm32f4xx.h"

int hse_start(void)
{
    RCC->CR |= RCC_CR_HSEON;

    for (uint32_t i = 0; i < 100000u; i++) {
        if (RCC->CR & RCC_CR_HSERDY) {
            return 0;
        }
    }
    RCC->CR &= ~RCC_CR_HSEON;
    return -1;
}

The function returns 0 once HSERDY is set, and -1 after the loop gives up and switches the oscillator off again, so the caller can fall back to the internal HSI. The loop count is a guard, not a time: choose it so that it is much longer than the crystal's start-up time in the datasheet at your clock speed.

For a clock supplied by another chip, set HSEBYP before HSEON; the bypass bit can only be changed while the oscillator is off (see the oscillator section of the reference manual for your part). The code was written against CMSIS Device F4 headers and STM32CubeF4 V1.28.

Taggedcstm32
Share

More snippets

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.