HeapCrash / Challenges / Battery voltage measurement

Battery voltage measurement

Li-ion cell (3.0–4.2 V) feeds a 3.3 V LDO powering the MCU. Battery voltage goes through a 1 MΩ/1 MΩ divider switched by a MOSFET. Readings are low and get stranger as the battery drains.

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 battery_mv(void)
{
    gpio_write(VBAT_EN, 1);
    uint32_t raw = adc_read(CH_VBAT);
    gpio_write(VBAT_EN, 0);
    return raw * 3300 / 4095 * 2;   /* 1:1 divider */
}

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