Simvik

UART baud-rate divisor

Compute the divisor that gives the closest baud rate. An easy embedded C problem (Registers and memory-mapped I/O), run and graded in the browser.

easy · Registers and memory-mapped I/O · uart · rounding

A UART with 16x oversampling produces baud = clock / (16 * divisor).

Return the integer divisor that gives the baud rate closest to the requested one: clock_hz / (16 * baud), rounded to the nearest integer.

Starter code

uint16_t baud_divisor(uint32_t clock_hz, uint32_t baud) {
  // clock / (16 * baud), rounded to nearest rather than truncated.
  return 0;
}

Example tests

9600 baud from 16 MHz

printf("%u\n", baud_divisor(16000000, 9600));

Expected output:

104

115200 baud from 16 MHz

printf("%u\n", baud_divisor(16000000, 115200));

Expected output:

9

Learn it first

  • Registers, volatile and const · How C talks to hardware: memory-mapped registers, what volatile and const promise, register structs and read-modify-write.

More Registers and memory-mapped I/O problems