Simvik

Detect the baud rate

Measure a 'U' character's bit times and snap to the nearest standard baud rate. A medium embedded C problem (UART), run and graded in the browser.

medium · UART · uart · baud · timing

Bootloaders often detect the baud rate automatically: the host first sends U (0x55), whose bits alternate, so with its start and stop bits the line changes level at every bit. A timer captures how long each level lasted.

Return the standard rate nearest to the measurement:

  1. The measured rate is 1,000,000 × n / sum (pulse widths are in microseconds), rounded to the nearest whole number.
  2. Pick the rate from 1200, 2400, 4800, 9600, 19200, 38400, 57600 and 115200 with the smallest relative error: |measured − rate| × 1000 / rate, in parts per thousand (rounded down).
  3. If even the best rate is more than 50 parts per thousand (5 %) off, or there are no pulses, return 0.

Starter code

uint32_t autobaud(const uint16_t *pulse_us, size_t n) {
  return 1000000u / pulse_us[0];
}

Example tests

9600 baud

const uint16_t p[] = { 104, 104, 104, 104, 104, 104, 104, 104, 104, 104 };
printf("%u\n", (unsigned)autobaud(p, 10));

Expected output:

9600

115200 baud with timer jitter

const uint16_t p[] = { 9, 8, 9, 9, 8, 9, 9, 8, 9, 9 };
printf("%u\n", (unsigned)autobaud(p, 10));

Expected output:

115200

Learn it first

  • UART · Baud rate, framing, errors, flow control and DMA reception.

More UART problems