定时器的基本定时功能
- 该函数库的目的就是在统一的地方配置,将配置的不同项放置在一个结构体内部
- 使用一个枚举来定义一个的别名
- 该库就是基本定时产生超时中断
bsp_time_base.h
c
#ifndef _BSP_BASE_TIME_H_
#define _BSP_BASE_TIME_H_
#include <stdint.h>
#include "n32l40x.h"
typedef enum
{
TIME_ID_1,
// TIME_ID_2,
// TIME_ID_3,
TIME_NUM//led数量
}TIME_ID;
typedef struct
{
TIM_Module* time;
uint32_t time_rcc;
uint16_t irq_x;
uint32_t period;//重载值
uint32_t prescaler;//预分频器
uint8_t it_update;//是否使能更新中断
}time_t;
/**
* 基本定时器初始化
*/
void bsp_time_init(time_t *ptime);
//一键初始化所有定时器
void bsp_timers_init(void);
#endif
bsp_time_base.c
c
#include "bsp_include.h"
#include "timer/bsp_time.h"
static time_t s_times[TIME_NUM] = {
{TIM7,RCC_APB1_PERIPH_TIM7,TIM7_IRQn,3200,10000,1},//1ms
};
/**
* 中断相关初始化.
*/
static void bsp_time_nvic_config(time_t *ptime)
{
NVIC_InitType NVIC_InitStructure;
/* Enable the TIM1 global Interrupt */
NVIC_InitStructure.NVIC_IRQChannel = ptime->irq_x;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 7;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
TIM_ConfigInt(ptime->time, TIM_INT_UPDATE, ENABLE);
}
static void bsp_time_rcc_config(time_t *ptime)
{
if(ptime->time==TIM1||ptime->time==TIM8)
{
RCC_EnableAPB2PeriphClk(ptime->time_rcc, ENABLE);
}
else
{
RCC_EnableAPB1PeriphClk(ptime->time_rcc, ENABLE);
}
}
/**
* 基本定时器初始化
*/
void bsp_time_init(time_t *ptime)
{
TIM_TimeBaseInitType TIM_TimeBaseStructure;
/* 定时器时钟分频PCLK1 = HCLK/4 */
// RCC_ConfigPclk2(RCC_HCLK_DIV4);
/* 1.时钟使能 */
bsp_time_rcc_config(ptime);
/* Compute the prescaler value */
// PrescalerValue = 0; //(uint16_t) (SystemCoreClock / 12000000) - 1;
/* Time 2.基本配置 */
TIM_TimeBaseStructure.Period = ptime->period;
TIM_TimeBaseStructure.Prescaler = ptime->prescaler;//预分频器
TIM_TimeBaseStructure.ClkDiv = 0;
TIM_TimeBaseStructure.CntMode = TIM_CNT_MODE_UP;
TIM_InitTimeBase(ptime->time, &TIM_TimeBaseStructure);
//3.使能更新中断
if(ptime->it_update)
{
bsp_time_nvic_config(ptime) ;
}
/* 4.TIM1 使能计数 */
TIM_Enable(ptime->time, ENABLE);
}
//一键初始化所有定时器
void bsp_timers_init(void)
{
for(int i=0; i<TIME_NUM; i++)
{
bsp_time_init(s_times+i);
}
}
static uint8_t bsp_time_get_id(TIM_Module *tim)
{
for(uint8_t x=0;x<TIME_NUM;x++)
{
if(tim ==s_times[x].time)
return x;
}
return 0xff;
}
//定时器中断集中处理函数
static void bsp_time_iaq(time_t *ptime)
{
if (TIM_GetIntStatus(ptime->time, TIM_INT_UPDATE) != RESET)
{
TIM_ClrIntPendingBit(ptime->time, TIM_INT_UPDATE);
}
}
void TIM7_IRQHandler(void)
{
uint8_t id=bsp_time_get_id(TIM7);
if(0XFF!=id)
{
bsp_time_iaq(s_times+id);
led_on_blink(LED1);
}
}