HeapCrash / Challenges / Settings and calibration in one page

Settings and calibration in one page

Settings live in the last 2 KB page of an STM32L4's internal flash, which programs in 8-byte double-words. Factory calibration was later put in the second half of the same page. After an update that grew the settings struct, units lost their calibration, and some silently kept old settings.

The code

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

#define CFG_PAGE  255u
#define CFG_ADDR  0x0807F800u          /* settings: first 1 KB of the page */
#define CAL_ADDR  0x0807FC00u          /* factory calibration: second 1 KB */

typedef struct {
    uint32_t magic;
    uint16_t setpoint[600];
    uint16_t hysteresis;
    uint16_t flags;
    uint32_t crc;
} cfg_t;

bool cfg_save(const cfg_t *c)
{
    HAL_FLASH_Unlock();
    FLASH_EraseInitTypeDef e = { .TypeErase = FLASH_TYPEERASE_PAGES,
                                 .Banks = FLASH_BANK_1, .Page = CFG_PAGE, .NbPages = 1 };
    uint32_t err;
    HAL_FLASHEx_Erase(&e, &err);
    const uint8_t *src = (const uint8_t *)c;
    for (uint32_t i = 0; i < sizeof(cfg_t); i += 8) {
        HAL_FLASH_Program(FLASH_TYPEPROGRAM_DOUBLEWORD, CFG_ADDR + i,
                          *(const uint64_t *)(src + i));
    }
    HAL_FLASH_Lock();
    return true;
}

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