Detailed explanation of STM32 basic timer

Time:2021-11-28

The most basic function of timer is to deal with things regularly. For example, regularly send USART data, regularly collect ad data, regularly detect IO port potential, and output waveform through IO port. It can realize very rich functions. Timer is a very powerful peripheral. It is used in different industries in different ways and has a wide range of knowledge.

01. Timer introduction

First, we can find the resources of the customizer in the stm32f207 data manual. From the figure below, we can see that stm32f207 has 10 general timers, 2 advanced timers and 2 basic timers.

Differences between different timers

The basic block diagram of timer can be seen in the user reference manual of stm32f207. The following figure is the view diagram of timer 1 & 8.

As can be seen from the above figure, different registers have different parameters, bit number, counting mode, DMA request, channel gain, complementary output and others. Which timer to choose in a specific project depends on the specific application scenario. The following mainly explains the basic timing function of the timer and selects timer 3. The principle of other timers is the same. If you understand the timing function of timer 3, you can understand other timers. For STM32 Series MCU, the peripherals are basically the same, and other MCU’s are similar. There are Zhaoyi innovation, Xintang technology, Shanghai smart microelectronics and so on in China.

02. Clock source

Basic timing function block diagram of timer.

①CK_ PSC is the timer clock timxclk, which is provided after frequency division by apb1 prescaler.

② Timer clock passes PSC   After prescaler, CK_ CNT, used to drive counter counting.

Counter CNT   It’s a 16   Bit counter, up, down, up / down counting mode, the maximum count value is 65535. When the count reaches the automatic reload register, an update event is generated and cleared to start counting from scratch.

④ Automatic reload register arr   Is a 16 bit register, which contains the maximum value that the counter can count. When the count reaches this value, if the interrupt is enabled, the timer will generate an overflow interrupt.

The timer is a counter, just as we use the heartbeat to roughly estimate the time. The heartbeat can be roughly regarded as 1s, so we count 60 times and the heartbeat passes 60 seconds. Where CK_ CNT clock is similar to heartbeat, and CNT counter is similar to heartbeat times. For an extremely simple example, we want to achieve 60 second timing, CK_ CNT is 1s. We set the CNT counter to count up and start the interrupt, because there will be an interrupt only when overflow, that is, when the count reaches 65535. Then we set the CNT counter to 65535-60 = 65475. If it starts in time, an interrupt will occur after 60 seconds. We set the automatic reload register arr to 65475. When the CNT counter overflows, the automatic reload register arr will be automatically loaded into the CNT counter, and the automatic cycle timing can be realized for 60 seconds.

After the above analysis, the key to accurate timing is CK_ CNT frequency, while CK_ CNT is divided by timer clock. Then we need to know the timer clock of timer3. We’ll look at the clock system. See the article for details《Analysis of stm32f207 clock system》, this article mainly explains how the 120m clock of the system is obtained from the external 25m crystal oscillator. The problem of APB peripheral clock is mentioned.

The timer is under the APB timer clock. Specifically, whether it is under the apb1 or apb2 clock, we can see the picture name stm32f20xblock diagram in the stm32f207 data manual.

From the above, we can see that timer3 is under apb1.

So let’s analyze the frequency of apb1

As can be seen from the above figure, the apb1 timer is obtained from the system 120m clock (the system clock is configurable, and we use the default 120m clock) through AHB frequency division and APB frequency division.

Mengxin may not understand the “error” in the red box above. First, a closing bracket is missing from the manual. After modification, it should be:

if(APBx presc == 1)
    X1
else
    X2

in other words

If the APB frequency division coefficient is 1, the frequency remains unchanged, and the frequency output by APB is the frequency of the clock under APB.

APB frequency division coefficient is not 1, frequency X2, APB output frequency multiplied by 2 is the frequency of clock under APB.

Next, we analyze the apb1 clock from the system_ The setsysclock function in stm32f2xx. C is as follows

/* HCLK = SYSCLK / 1*/
RCC->CFGR |= RCC_CFGR_HPRE_DIV1;
    
/* PCLK2 = HCLK / 2*/
RCC->CFGR |=RCC_CFGR_PPRE2_DIV2;
    
/* PCLK1 = HCLK / 4*/
RCC->CFGR|= RCC_CFGR_PPRE1_DIV4;

It can be seen that the frequency division coefficient of AHB is 1 and that of apb1 is 4.

The clock of timer3 is 120m / 1 / 4 * 2 = 60MHz.

There is a question here. The system provided by St_ Stm32f2xx. C notes why it is hclk, pclk2, pclk1, but there are no APB and AHB words mentioned above. Please see the article I wrote before《Analysis of stm32f207 clock system》。

In fact, we have the analysis code, system_ The stm32f2xx. C file header is also annotated for easy viewing.

Of course, this requires our external crystal oscillator to be 25m and system_ Stm32f2xx. C has not been modified. If you need to modify this file, the MCU runs overclocking, it is recommended to modify the comments in the file header to form a good habit.

03. Time base unit

The programmable advanced timer control module is mainly a 16 bit counter with related automatic overload. This counter can count up, down, or alternately up and down. The counter clock can be divided by a frequency divider.

The automatic overload register and prescaler register of the counter can be read and written by software. It can read and write even when the counter is running.

The time base unit includes

  1. Counter register   (TIMx_CNT)

  2. Prescaler register   (TIMx_PSC)

  3. Automatic reload register   (TIMx_ARR)

  4. Repeat counter register   (TIMx_RCR)

The auto reload register is preloaded. Writing or reading from the auto reload register accesses the preload register. The contents of the preloaded register can be transferred either directly to the shadow register or to the shadow register every time an update event (UeV) occurs, depending on timx_ CR1   The auto reload preload enable bit (ARPE) in the register. When the counter reaches an overflow value (or an overflow value is reached when the count is decremented) and timx_ CR1   Udis in register   When the bit is 0, an update event is sent. The update event can also be generated by the software.

The counter is output by the prescaler_ CNT   Provide clock, only if timx_ CR1   The counter start bit (CEN) in the register is set to 1   The counter will only be started when.

Prescaler description

The prescaler can divide the clock frequency of the counter, and the frequency division coefficient is between 1   And 65536   between. The prescaler is based on timx_ 16 in PSC register   16 bit counter controlled by bit register. Since the control register has a buffer function, the prescaler can be changed in real time. The new prescaler will be adopted when the next update event occurs.

The following figure illustrates the behavior of the counter when the prescaler changes in real time.

Prescaler 1   Change to 2   Counter timing diagram at

Prescaler 1   Change to 4   Counter timing diagram at

04. Counting mode

4.1. Count up mode

In the count up mode, the counter increases from 0 to the auto reload value (the value of the timx_arr register), then restarts from 0 and generates a counter overflow event.

If a repeat counter is used, an update event (UeV) is generated when the number of repetitions counted up reaches the number programmed in the repeat counter register plus one (timx_rcr + 1). Otherwise, an update event will be generated each time the counter overflows.

Set timx_ When UG position 1 of EGR register is passed through software or slave mode controller is used, an update event will also be generated.

Timx through software_ Udis position 1 in the CR1 register disables UeV events. This avoids updating the shadow register when a new value is written to the preload register. No update event is generated until the udis bit is written to 0. However, both the counter and prescaler counter start counting again from 0 (while the prescaler ratio remains unchanged). In addition, if timx_ If the urs bit (update request selection) in the CR1 register is set to 1, setting UG position 1 will generate an update event UeV, but the UIF flag will not be set to 1 (therefore, no interrupt or DMA request will be sent). In this way, if the counter is cleared when a capture event occurs, there will be no update interrupt and capture interrupt at the same time.

When an update event occurs, all registers are updated and the update flag (UIF bit in timx_sr register) is set to 1 (depending on urs bit)

  1. Timx will be reloaded in the repeat counter_ Contents of RCR register

  2. Automatically reloading shadow registers will preload values   (TIMx_ARR)   Update

  3. The pre loaded value (the contents of the timx_psc register) will be reloaded in the buffer of the prescaler

Counter timing diagram, 1   Frequency division internal clock

Counter timing diagram, 2   Frequency division internal clock

It can be seen from the above two figures that the interrupt flag needs to be cleared by software

Counter sequence diagram, ARPE = 0   Update event on (timx_arr)   (not preloaded)

As can be seen from the above two figures, if you count up and change the automatic overload register to 0x36 before reaching 0x36, an action will be generated when the count reaches 0x36.

Counter sequence diagram, ARPE = 1   Update event on (timx_arr)   (preload)

It can be seen from the above two figures that when counting up, the automatic reload preload register is modified to 0x36 before it reaches 0x36, there will be no action when counting to 0x36, and the automatic reload preload register value will be assigned to the automatic reload shadow register at this time.

4.2. Down counting mode

In the count down mode, the counter counts down from the auto reload value (the value of the timx_arr register) to 0, then restarts from the auto reload value (and generates a counter overflow event.

If a repeat counter is used, an update event (UeV) is generated when the number of repetitions counted down reaches the number programmed in the repeat counter register plus one (timx_rcr + 1). Otherwise, an update event will be generated each time the counter overflows.

Set timx_ EGR   UG of register   An update event will also occur at position 1 (via software or using the slave mode controller).

Timx through software_ CR1   Udis in register   Position 1   UeV can be disabled   Update events. This avoids updating the shadow register when a new value is written to the preload register. In udis   No update event is generated until the bit is written to 0. However, the counter starts counting again from the current auto reload value, and the prescaler counter starts counting again from 0   Start counting (but the prescaler ratio remains unchanged).

In addition, if timx_ CR1   Urs in register   If the bit (update request selection) is set to 1, UG   Position 1   An update event UeV is generated, but the UIF is not   Flag set to 1 (therefore, no interrupt or DMA will be sent   Request). In this way, if the counter is cleared when a capture event occurs, there will be no update interrupt and capture interrupt at the same time.

When an update event occurs, all registers are updated and flags (timx_sr) are updated   UIF in register   Bit) set to 1 (depending on   URS   Bits):

  1. The repeat counter will be reloaded   TIMx_ RCR   Contents of register

  2. The preload value will be reloaded in the buffer of the prescaler(   TIMx_PSC   Contents of register)

  3. The auto reload active register will be loaded with the preload value(   TIMx_ARR   Register contents). Note that the auto reload register will be updated before the counter is reloaded, so the next count cycle is the new cycle length we want

The following figures illustrate timx with some examples_ ARR=0x36   Counter behavior at different clock frequencies

Counter timing diagram, 1   Frequency division internal clock

Counter timing diagram, 2   Frequency division internal clock

Counter timing chart, updating events when duplicate counters are not used

4.3. Center alignment (count up / down mode)

In center alignment mode, the counter changes from 0   Start counting to auto reload value (timx_arr)   Register contents) – 1, generate counter overflow event; Then count down to 1 from the automatic overload value   And generate a counter underflow event. Then start counting again from 0.

When timx_ CR1   The center alignment mode is valid when the CMS bit in the register is not “00”. When the channel is configured as output mode, its output comparison interrupt flag will be set to 1 in the following modes: counter down count (center aligned mode 1, CMS = “01”), counter up count (center aligned mode 2, CMS = “10”) and counter up / down count (center aligned mode 3, CMS = “11”).

In this mode, timx_ CR1   Dir of register   The direction bit is not a writable value, but is updated by the hardware and indicates the current counter direction.

An update event is generated each time a counter overflow or underflow occurs, or timx_ EGR   UG in register   Location 1 (via software or using slave mode controller) can also generate update events. In this case, the counter and prescaler counter will be reset from 0   Start counting.

Timx through software_ CR1   Udis in register   Position 1   UeV can be disabled   Update events. This avoids updating the shadow register when a new value is written to the preload register. In udis   Bit write 0   No update events will be generated before. However, the counter still counts up and down based on the current auto reload value.

In addition, if timx_ CR1   Urs in register   If the bit (update request selection) is set to 1, UG   Position 1   UeV will be generated   Updates the event, but does not change the UIF   Flag set to 1 (therefore, no interrupt or DMA will be sent   Request). In this way, if the counter is cleared when a capture event occurs, there will be no update interrupt and capture interrupt at the same time.

When an update event occurs, all registers are updated and flags (timx_sr) are updated   UIF in register   Bit 1 (depending on URS)   Bits):

  1. The repeat counter will be reloaded   TIMx_ RCR   Contents of register

  2. The preload value will be reloaded in the buffer of the prescaler(   TIMx_PSC   Contents of register)

  3. The auto reload active register will be loaded with the preload value(   TIMx_ARR   Register contents). Note that if the update operation is triggered by counter overflow, the automatic reload register is updated before overloading the counter. Therefore, the next count cycle is the new cycle length we want (the counter is overloaded with a new value).

The following figures illustrate the behavior of counters at different clock frequencies with some examples

Counter timing diagram, 1   Frequency division internal clock, timx_ ARR = 0x6

Counter timing diagram, 2   Frequency division internal clock

Counter sequence diagram, ARPE = 1   Update event at (counter underflow)

Counter sequence diagram, ARPE = 1   Update event at (counter overflow)

05. Basic timing code

10ms interrupt configuration code

About setting frequency division value

TIM3CLK = 2 * PCLK1=2*HCLK / 4= HCLK / 2 = SystemCoreClock /2=60MHZ

So tim3clk is in the red box below

The value here is the frequency division coefficient = tim3clk / actual timer frequency, so the timer frequency is 10000, that is, the divisor is the timer frequency. A CLK is 1 / 10000 s. Timing time = 1 / 10000 * timer overload value. According to the above configuration, the timer overload value is 100, that is, the timer interrupt cycle is = 1 / 10000 * 100 = 0.01s = 10ms, that is, 100Hz.

If the LED is turned over at the timer, the flashing frequency of the LED is 50Hz.

Of course, the above frequency division value can be directly assigned 5999. If you want to modify the timer frequency to 1000, you have to recalculate it. If you follow the above method, you can directly modify the divisor to 1000.

You will have questions here. The overload value given is obviously 99, and the frequency division rate value is minus 1. The reason why 1 needs to be subtracted from both the frequency division value and the automatic reload cycle value will be explained below.

Automatic overload value: because it is calculated from 0 and assigned 10, it is 11 times to count from 0 to 10.

Frequency division value: in timx_ The PSC register has the following description.

Special note

Clock division

TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV2;

In fact, after carefully reading the technical manual, it is found that this sentence has nothing to do with the PWM output experiment. This sentence sets the frequency division ratio between the timer clock (ck_int) frequency and the sampling frequency used by the digital filter (ETR, tix) (related to input acquisition). 0 indicates that the frequency of the filter is the same as that of the timer.

First, this colck_ The division clock division coefficient does not divide the clock frequency of the timer. We all know that there is a digital filter in the input capture mode. This digital filter can filter out some frequencies by changing its sampling frequency through the configuration register.

The details are explained in the input capture.

We can also use the method of querying the counter to achieve accurate delay according to the characteristics of the timer counter. For details, see《Four methods of STM32 delay function》。

Timer code open source address:

https://github.com/strongercjd/STM32F207VCT6

Click to view the album where this article is located,Stm32f207 tutorial

Recommended Today

On the mutation mechanism of Clickhouse (with source code analysis)

Recently studied a bit of CH code.I found an interesting word, mutation.The word Google has the meaning of mutation, but more relevant articles translate this as “revision”. The previous article analyzed background_ pool_ Size parameter.This parameter is related to the background asynchronous worker pool merge.The asynchronous merge and mutation work in Clickhouse kernel is completed […]