Simvik

Start the crystal, or fall back

Switch to an external crystal with a timeout, fall back to the internal oscillator, and set the baud rate for whichever clock you got. A medium embedded C…

medium · Board bring-up, step by step · bring-up · clocks · timeout · uart

A crystal that does not start (a wrong load capacitor, a cracked part) must not hang the board forever. Write:

  • clock_start(): set HSEON in CR, then read CR until HSERDY is set, at most HSE_TIMEOUT times. If it becomes ready, select the HSE in RCC_CFGR's SW field (keep the other bits) and return HSE_HZ. If not, clear HSEON again, leave the system clock on the HSI and return HSI_HZ.
  • uart_brr(clk_hz, baud): the UART's divider for the clock it really has, clk_hz / baud rounded to the nearest integer.

Starter code

uint32_t clock_start(void) {
  rcc_cr_write(rcc_cr_read() | RCC_CR_HSEON);
  while (!(rcc_cr_read() & RCC_CR_HSERDY)) {
  }
  RCC_CFGR = RCC_CFGR_SW_HSE;
  return HSE_HZ;
}

uint32_t uart_brr(uint32_t clk_hz, uint32_t baud) {
  return clk_hz / baud;
}

Example tests

A good crystal

boot(50);

Expected output:

clock 25000000 brr 217 sw=1 hseon=1 cfgr=0x00009401

A crystal that never starts

boot(-1);

Expected output:

clock 16000000 brr 139 sw=0 hseon=0 cfgr=0x00009400

Learn it first

More Board bring-up, step by step problems