Delay using general purpose timer - faster than expected

337 Views Asked by At

I've written a delay function using one of the basic timers on my nucleo-g070 board (not systick). The default clock is 16MHz (if I query the APB1 frequency I get 16000000). However, the LED blinks way too fast (almost too fast to see), so something's really wrong.

Here's the code:

void delay_setup(void) {
    rcc_periph_clock_enable(RCC_TIM6);
    timer_set_prescaler(TIM6, rcc_apb1_frequency / 1000000 - 1);
    timer_set_period(TIM6, 0xffff);
    timer_one_shot_mode(TIM6);
}

void delay_us(uint32_t us) {
    TIM_ARR(TIM6) = us;
    TIM_EGR(TIM6) = TIM_EGR_UG;
    TIM_CR1(TIM6) |= TIM_CR1_CEN;
    while (TIM_CR1(TIM6) & TIM_CR1_CEN);
}

I have tried other timers too with the same result. However, a strange thing happened - I wrote TIM2 by mistake (not knowing the MCU doesn't have it) and I got the expected 1s delay. Again, in the datasheet there's no TIM2 specified. So what's going on here?

0

There are 0 best solutions below