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:
- The measured rate is
1,000,000 × n / sum(pulse widths are in microseconds), rounded to the nearest whole number. - 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). - 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:
9600115200 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:
115200Learn it first
- UART · Baud rate, framing, errors, flow control and DMA reception.
More UART problems
- Assemble command lines · Collect received characters into lines, with backspace and overflow handled.
- Parse a modem signal report · Validate a +CSQ reply and convert it to dBm.
- Interrupt-driven transmit queue · Queue bytes for the UART and send them from the data-register-empty interrupt.
- Spot OK and ERROR in a modem stream · Feed received characters one at a time and report complete OK or ERROR lines.
- Driver: a polled UART transmitter · Configure a UART from its register map and send bytes without losing any.
- Driver: receive bytes and detect an overrun · Read the UART's receive register without blocking, and report lost bytes.
- Fix: lost bytes are never reported · A receive routine checks the data flag before the overrun flag, so overruns disappear.
- Command console · Split a command line into words, with quoted arguments, and dispatch it through a command table.
- Greenhouse: parse a console command · Parse a technician's command line, and refuse anything malformed or out of range.