HeapCrash / Challenges / Building a framed packet

Building a framed packet

Spec: SOF, CMD, LEN, payload, then CRC-16/CCITT-FALSE computed over CMD, LEN and payload only, sent MSB first. The CRC function itself has been verified against test vectors.

The code

Embedded C for Cortex-M. It compiles. There are 3 real bugs in it: the kind that pass a bench test and fail in the field.

uint16_t crc16_ccitt(const uint8_t *d, size_t n)
{
    uint16_t crc = 0xFFFF;
    for (size_t i = 0; i < n; i++) {
        crc ^= (uint16_t)d[i] << 8;
        for (int b = 0; b < 8; b++)
            crc = (crc & 0x8000) ? (crc << 1) ^ 0x1021 : crc << 1;
    }
    return crc;
}

void send_packet(uint8_t cmd, const uint8_t *p, uint8_t n)
{
    uint8_t frame[64];
    frame[0] = SOF;
    frame[1] = cmd;
    frame[2] = n;
    memcpy(&frame[3], p, n);
    uint16_t crc = crc16_ccitt(frame, n + 3);
    memcpy(&frame[3 + n], &crc, 2);
    uart_send(frame, n + 5);
}

What an interviewer expects

The bugs, reference fixes and the follow-up question are in the practice app, after you've tried it.

Companies that test this

Matched on the skills each company's embedded roles emphasise.

Related challenges

Flag the lines, say what breaks, then fix it and build it with clang in your browser.

Find the bugs