Build a UART frame
Assemble the bits a UART sends for one byte with parity. A medium embedded C problem (Protocols, framing and checksums), run and graded in the browser.
medium · Protocols, framing and checksums · uart · parity
A UART configured as 8 data bits, parity, 1 stop bit sends 11 bits per byte, in this order: a start bit (0), the eight data bits least significant first, the parity bit, and a stop bit (1).
Return the frame as a 16-bit value in which bit 0 is the first bit on the wire. With even_parity true, the parity bit makes the total number of 1 bits in the data plus parity even; otherwise it makes that number odd.
Starter code
uint16_t uart_frame(uint8_t data, bool even_parity) {
// bit 0 = start (0), bits 1..8 = data LSB first, bit 9 = parity, bit 10 = stop (1)
return 0;
}Example tests
Even parity, even number of ones
printf("0x%04X\n", uart_frame(0x55, true));Expected output:
0x04AAEven parity, odd number of ones
printf("0x%04X\n", uart_frame(0x01, true));Expected output:
0x0602Learn it first
- Protocols, framing and checksums · Checksums, CRCs, byte order, framing and parsing a byte stream.
More Protocols, framing and checksums problems
- XOR checksum · Compute the XOR of every byte in a buffer.
- Two's-complement checksum · Compute the checksum byte of an Intel HEX record.
- CRC-8 · Implement a bitwise CRC-8 with polynomial 0x07.
- CRC-16 for Modbus · Implement the reflected CRC-16 used by Modbus RTU.
- Read a big-endian word · Assemble a 32-bit value from four bytes of a packet.
- I2C address byte · Build the first byte of an I2C transfer.
- BCD conversion · Convert between binary-coded decimal and binary.
- Build a framed message · Wrap a payload with a start byte, a length and a checksum.
- SLIP byte stuffing · Escape reserved bytes so a frame delimiter is unambiguous.
- Variable-length integer · Encode a 32-bit value in as few bytes as it needs.
- Validate an NMEA sentence · Check the checksum of a GPS sentence.
- Byte-stream frame parser · Reassemble frames from a byte stream one byte at a time.
- COBS encoding · Remove every zero byte from a packet with one byte of overhead.
- Fix: the bootloader hangs on large chunks · A loop counter is too narrow for the length it counts to.
- Fix: frame lengths come out 256 times too big · A big-endian length field is decoded as little-endian.
- Reliable delivery over a lossy link · Stop-and-wait with a sequence bit, acknowledgements, a retransmit timer and duplicate detection.
- Solar inverter: decode a status frame · Check a frame from the inverter and decode its power, voltage and temperature.