japaric / stm32f103xx-hal

HAL for the STM32F103xx family of microcontrollers
Apache License 2.0
115 stars 40 forks source link

Timer prescaler out of order #57

Closed TheZoq2 closed 6 years ago

TheZoq2 commented 6 years ago

I have had some issues with timers which I have narrowed down to being caused by the timer prescaler not being set until the next countdown starts (or something along those lines).

The following code works. It sets the pin to high for 8 milliseconds followed by it being low for 1 millisecond as expected.

loop {
    pin.set_high();
    timer2.start(Hertz(125));
    block!(timer2.wait()).unwrap();
    pin.set_low();
    timer2.start(Hertz(1000));
    block!(timer2.wait()).unwrap();
}

However, if I change the frequency of timer1 to 111 Hz the pin is only high for 4.5 ms and is low for 2 ms, rather than 9ms -> 1ms as expected.

The difference between 111 Hz and 125 Hz is that at 125 Hz, the prescaler is set to 0 while it is set to 1 at 111 Hz. This is to be expected because at the frequency of the clock, 111 Hz requires more than a 16 bit value to store and hence the prescaler gets set.

However, as the example shows, the prescaler is "delayed". The value 0 which is supposed to be used for the first call is used for the second, and the value 1 is used for the first instead.