HeapCrash / Challenges / Microsecond delays that hang

Microsecond delays that hang

A stepper driver needs a 2 µs STEP pulse and 5 ms settling after the driver is enabled. delay_us uses the DWT cycle counter at 160 MHz. With the debugger attached everything works. Running standalone, the first step never finishes. In long runs a step pulse occasionally comes out far too short, and pressing the enable button locks the board.

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 delay_us(uint32_t us)
{
    uint32_t start = DWT->CYCCNT;
    uint32_t cycles = us * (SystemCoreClock / 1000000u);
    while (DWT->CYCCNT < start + cycles) { }
}

void step_pulse(void)
{
    HAL_GPIO_WritePin(GPIOA, STEP_PIN, GPIO_PIN_SET);
    delay_us(2);
    HAL_GPIO_WritePin(GPIOA, STEP_PIN, GPIO_PIN_RESET);
}

void EXTI0_IRQHandler(void)          /* enable button */
{
    EXTI->PR1 = EXTI_PR1_PIF0;
    HAL_GPIO_WritePin(GPIOA, DRV_EN_PIN, GPIO_PIN_SET);
    HAL_Delay(5);
    step_pulse();
}

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