cancel
Showing results for 
Search instead for 
Did you mean: 

Delay function using timers - LED blinks too fast

BSerb
Associate II
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've written this function that implements a us delay using one of the timers on my nucleo-g070 board. However, when I call a 1s delay, the LED blinks way too fast (almost imperceptible). The clock is set at 16MHz (checked).

However, a strange thing happened. I accidentally changed TIM6 to TIM2 and the LED blinked at 1s interval as it should. But when I checked the datasheet, there's no TIM2 for this MCU...

The library is libopencm3, but I checked the functions and they do what they're supposed to do.

1 REPLY 1

> when I call a 1s delay

That's one million microseconds. The TIM6 is 16-bits, so it strips whatever is above 65535, i.e. it waits 1000000 mod 65536 = 16960us, cca 17ms. If you use it for blinking, it's results in 30Hz blink, that's exactly "almost imperceptible".

TIM2 is 32-bit so it waits the 1000000 cycles as expected.

The 'G0x0 is a low-cost version of 'G0x1. The TIM2 is there, it's just not tested, i.e. not guaranteed to work - which means it's as good as it wouldn't be there.

JW