1.开启时钟
2.配置定时器参数
3.配置中断优先级
4.使能中断和定时器
定时器5为例
\brief configure the TIMER clock prescaler selection
\param[in] timer_clock_prescaler: TIMER clock selection
only one parameter can be selected which is shown as below:
\arg RCU_TIMER_PSC_MUL2: if APB1PSC/APB2PSC in RCU_CFG0 register is 0b0xx(CK_APBx = CK_AHB)
or 0b100(CK_APBx = CK_AHB/2), the TIMER clock is equal to CK_AHB(CK_TIMERx = CK_AHB).
or else, the TIMER clock is twice the corresponding APB clock (TIMER in APB1 domain: CK_TIMERx = 2 x CK_APB1;
TIMER in APB2 domain: CK_TIMERx = 2 x CK_APB2)
\arg RCU_TIMER_PSC_MUL4: if APB1PSC/APB2PSC in RCU_CFG0 register is 0b0xx(CK_APBx = CK_AHB),
0b100(CK_APBx = CK_AHB/2), or 0b101(CK_APBx = CK_AHB/4), the TIMER clock is equal to CK_AHB(CK_TIMERx = CK_AHB).
or else, the TIMER clock is four timers the corresponding APB clock (TIMER in APB1 domain: CK_TIMERx = 4 x CK_APB1;
TIMER in APB2 domain: CK_TIMERx = 4 x CK_APB2)
\param[out] none
\retval none
prescaler | 这个参数是时钟的预分频值,是16位的,取值范围为1-65535。 prescaler参数将决定一个计数周期的时间。设预分频值为pre,则计数器时钟频率PSC_CLK=TIMER_CK / (pre + 1)。 |
alignedmode | 对齐模式 |
counterdirection | 计数模式,基本定时器只有向上计数模式,所以配置为TIMER_COUNTER_UP。 |
clockdivision | 时钟分频,在输入捕获的时候使用,定时器时钟频率与死区发生器和数字滤波器使用的采样频率之间的分频比。 |
period | 周期值,是一个16位的计数器,最大值为65535,当计数器达到设置的周期数值(自动重装载寄存器)时数值清零,配合计数器时钟频率可以计算中断时间。 |
repetitioncounter | 重复计数器(只有高级定时器有),取值范围为0-255,配置为x,就重复x+1次才进入中断。 |
bsp_timer.c文件
#include "bsp_timer.h"
#include "stdio.h"
void bsp_timer_config(uint16_t pre,uint16_t per)
{
/* 一个周期的时间T = 1/f, 定时时间time = T * 周期
设预分频值位pre,周期位per
time = (pre + 1) * (per + 1) / psc_clk
*/
timer_parameter_struct timere_initpara; // 定义定时器结构体
/* 开启时钟 */
rcu_periph_clock_enable(RCU_TIMER5); // 开启定时器时钟
/* CK_TIMERx = 4 x CK_APB1 = 4x50M = 200MHZ */
rcu_timer_clock_prescaler_config(RCU_TIMER_PSC_MUL4); // 配置定时器时钟
timer_deinit(TIMER5); // 复位定时器
/* 配置定时器参数 */
timere_initpara.prescaler = pre-1; // 时钟预分频值 0-65535 psc_clk = CK_TIMER / pre
timere_initpara.alignedmode = TIMER_COUNTER_EDGE; // 边缘对齐
timere_initpara.counterdirection = TIMER_COUNTER_UP; // 向上计数
timere_initpara.period = per-1; // 周期
/* 在输入捕获的时候使用 数字滤波器使用的采样频率之间的分频比例 */
timere_initpara.clockdivision = TIMER_CKDIV_DIV1; // 分频因子
/* 只有高级定时器才有 配置为x,就重复x+1次进入中断 */
timere_initpara.repetitioncounter = 0; // 重复计数器 0-255
timer_init(TIMER5,&timere_initpara); // 初始化定时器
/* 配置中断优先级 */
nvic_irq_enable(TIMER5_DAC_IRQn,3,2); // 设置中断优先级为 3,2
/* 使能中断 */
timer_interrupt_enable(TIMER5,TIMER_INT_UP); // 使能更新事件中断
/* 使能定时器 */
timer_enable(TIMER5);
}
void BSP_TIMER_IRQHANDLER(void)
{
/* 这里是定时器中断 */
if(timer_interrupt_flag_get(TIMER5,TIMER_INT_FLAG_UP) == SET)
{
timer_interrupt_flag_clear(TIMER5,TIMER_INT_FLAG_UP); // 清除中断标志位
/* 执行功能 */
gpio_bit_toggle(GPIOD,GPIO_PIN_7); // 翻转led
}
}
bsp_timer.h文件
#ifndef _BSP_TIMER_H
#define _BSP_TIMER_H
#include "gd32f4xx.h"
#include "systick.h"
void bsp_timer_config(uint16_t pre,uint16_t per); // 基本定时器配置
#endif
在main.c文件 #include "bsp_timer.h"。main函数调用:bsp_timer_config(20000,10000); // 定时器初始化。
定时时间 = 20000 / 200 * 10000us = 1s