HeapCrash / Challenges / Saving settings to internal flash

Saving settings to internal flash

STM32L4 internal flash, rated for about 10,000 erase cycles. save_setpoint is called from the UI on every encoder detent. The UI freezes briefly while turning the knob.

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.

void save_setpoint(int16_t sp)
{
    HAL_FLASH_Unlock();
    FLASH_EraseInitTypeDef e = { .TypeErase = FLASH_TYPEERASE_PAGES,
                                 .Page = CFG_PAGE, .NbPages = 1 };
    uint32_t err;
    HAL_FLASHEx_Erase(&e, &err);
    HAL_FLASH_Program(FLASH_TYPEPROGRAM_DOUBLEWORD, CFG_ADDR, sp);
    HAL_FLASH_Lock();
}

int16_t load_setpoint(void)
{
    return *(int16_t *)CFG_ADDR;
}

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