HeapCrash / Challenges / 64-bit microsecond timestamps

64-bit microsecond timestamps

A 32-bit timer counts microseconds and an overflow interrupt extends it to 64 bits. Logs occasionally show time jumping backwards by about 71 minutes.

The code

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

static volatile uint32_t overflow_count;

void TIM2_IRQHandler(void)
{
    if (TIM2->SR & TIM_SR_UIF) {
        TIM2->SR = ~TIM_SR_UIF;
        overflow_count++;
    }
}

uint64_t micros64(void)
{
    return ((uint64_t)overflow_count << 32) | TIM2->CNT;
}

static volatile uint64_t g_last_event_us;   /* written in an EXTI ISR */

uint64_t last_event_us(void)
{
    return g_last_event_us;
}

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