Clocks are generally divided into external crystal oscillator clocks and internal clocks. Relatively speaking, the accuracy of external crystal oscillator clocks is higher than that of internal system clocks, and time calculation is more accurate. Unless the product requires it, an external crystal oscillator clock is generally not used, because good things are expensive and costly.
This article mainly introduces how to use the clock to set Timer0/1 (RTC, PWM interrupt, ADC), and how to set the interrupt time.
Basic knowledge 1 MHz=1000 kHz=1000 000 Hz 1s = 1 000ms
Before selecting the timer function, you must select the clock , and then select the frequency division to determine the interrupt time .
Table of contents
2.2.1 PLL frequency division configuration
2.2.2 TIMER0/1 Get frequency division selection
3. Calculate the interruption time
3.1 RC_32KHz calculation interrupt time
3.2 RC_1MHz calculation interrupt time
1. Clock structure
As shown below:
RC32KHz (RC128KHz4 frequency division) is a low-speed clock (low power mode),
RC1MHz is the system clock (can be connected to each module),
XOSC is the external crystal oscillator clock
2. Set Timer0/1 clock
Select the clock according to the chip manual
2.1, RC32K (low power clock)
Low-power clock, RC_128K, RC_32K after 4 frequency division of 128kHZ
2.2, RC1M (system clock)
2.2.1 PLL frequency division configuration
RC1M input to PLL1MHz, output 32MHZ
RC 1MHz→PLL 32MHz is selected as shown in the figure, if it is not checked, the register must be configured.
We see that there is no frequency division of the external clock in the PLL register, which proves that the chip has no external crystal oscillator clock.
2.2.2 TIMER0/1 Get frequency division selection
PLL outputs 32MHz to G, and then chooses to divide by 2 to TIMER0/1.
Initialize check or register selection
3. Calculate the interruption time
3.1 RC_32KHz calculation interrupt time
32KHz = 32 000 Hz, then 1 S is 32 000 Hz (0x7D00), 1ms is 32 Hz (0x20)
3.2 RC_1MHz calculation interrupt time
RC_1MHZ → 1MHZ → PLL (32MHz) → G (2 frequency division) → 16MHz
1S is 16MHz 16MHz = 16 000 000Hz 1ms is 16 000Hz (0X3E80)
/*!
\brief timer0/1 initialize
\param[in] timerx: TIMERx(0,1)
\param[in] timer_cfg: timer0/1 config
\param[in] timer_mod: timer0/1 mod count
\param[out] none
\retval none
*/
void timer_init(uint32_t timerx,uint8_t timer_cfg,uint16_t timer_mod)
{
TIMER_CFG(timerx) = timer_cfg;
TIMER_MOD(timerx) = timer_mod;
if(timerx == (uint32_t)TIMER0){
if((timer_cfg & TIMER_CFG_IE) != 0U){
NVIC_EnableIRQ(TIMER0_IRQn);
}else{
NVIC_DisableIRQ(TIMER0_IRQn);
}
}else{
if((timer_cfg & TIMER_CFG_IE) != 0U){
NVIC_EnableIRQ(TIMER1_IRQn);
}else{
NVIC_DisableIRQ(TIMER1_IRQn);
}
}
}
timer_init(TIMER0,0x2B,0x3E80); 0X2B is configured for each register, and 0x3E80 generates an interrupt for 1ms.
Other interrupt events are basically the same, just imitate.