HeapCrash / Challenges / ADC over spidev

ADC over spidev

A userspace daemon reads an MCP3008 8-channel ADC through /dev/spidev0.0. Readings are right most of the time, but on some boots every reading is garbage or zero. A configuration typo that asked for channel 8 silently returned something that looked like channel 0.

The code

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

int adc_read(int fd, int ch, uint16_t *out)
{
    uint8_t tx[3] = { 0x01, (uint8_t)((8 + ch) << 4), 0x00 };
    uint8_t rx[3];
    struct spi_ioc_transfer t;
    t.tx_buf = (unsigned long)tx;
    t.rx_buf = (unsigned long)rx;
    t.len = 3;
    t.speed_hz = 1000000;
    ioctl(fd, SPI_IOC_MESSAGE(1), &t);
    *out = (uint16_t)(((rx[1] & 0x03) << 8) | rx[2]);
    return 0;
}

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