1.简介
1. 基本定时器 TIM6 和 TIM7 包含一个 16 位自动重载计数器
2. 可以专门用于驱动数模转换器 (DAC), 用于触发 DAC 的同步电路
3. 16 位自动重载递增计数器4. 16 位可编程预分频器
5. 计数器溢出时, 会触发中断/DMA请求
从上往下看
1.开始RCC供给定时器的时钟
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM6,ENABLE);
2.设置预分频值PSC,重装载值,计数方向
TIM_TimeBaseInitStructure.TIM_Period = arr; //自动重装载值
TIM_TimeBaseInitStructure.TIM_Prescaler=psc; //定时器分频
TIM_TimeBaseInitStructure.TIM_CounterMode=TIM_CounterMode_Up; //向上计数模式
TIM_TimeBaseInitStructure.TIM_ClockDivision=TIM_CKD_DIV4;TIM_TimeBaseInit(BASE_TIMER,&TIM_TimeBaseInitStructure);//初始化TIM6
注意,对于基本定时器TIM6, TIM 7, TIM_TimeBaseInitStructure.TIM_ClockDivision是无效的, 供给的时钟到预分频器的前面没有分频.在通用定时器和高级定时器中TIMx_CR1的位 9:8 CKD:时钟分频 (Clock division)对输入时钟进行首次分频
3.开启更新中断,使能定时器
TIM_ITConfig(BASE_TIMER,TIM_IT_Update,ENABLE); //允许定时器3更新中断
TIM_Cmd(BASE_TIMER,ENABLE); //使能定时器3
4.设置中断优先级
NVIC_InitStructure.NVIC_IRQChannel=TIM6_DAC_IRQn; //定时器6中断
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority=0x01; //抢占优先级1
NVIC_InitStructure.NVIC_IRQChannelSubPriority=0x03; //子优先级3
NVIC_InitStructure.NVIC_IRQChannelCmd=ENABLE;
NVIC_Init(&NVIC_InitStructure);
5.例程
#include "./BaseTime/basetime.h"
#include "./LED/led.h"
#define BASE_TIMER TIM6
#define BASE_TIMER_CLK RCC_APB1Periph_TIM6
#define BASE_TIME_IRQ TIM6_DAC_IRQn
#define BASE_TIME_IRQHandler TIM6_DAC_IRQHandler
void bsTime_Init(u16 arr,u16 psc)
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
RCC_APB1PeriphClockCmd(BASE_TIMER_CLK,ENABLE); ///使能TIM6时钟
TIM_TimeBaseInitStructure.TIM_Period = arr; //自动重装载值
TIM_TimeBaseInitStructure.TIM_Prescaler=psc; //定时器分频
TIM_TimeBaseInitStructure.TIM_CounterMode=TIM_CounterMode_Up; //向上计数模式
TIM_TimeBaseInitStructure.TIM_ClockDivision=TIM_CKD_DIV4;
TIM_TimeBaseInit(BASE_TIMER,&TIM_TimeBaseInitStructure);//初始化TIM6
TIM_ITConfig(BASE_TIMER,TIM_IT_Update,ENABLE); //允许定时器3更新中断
TIM_Cmd(BASE_TIMER,ENABLE); //使能定时器3
NVIC_InitStructure.NVIC_IRQChannel=BASE_TIME_IRQ; //定时器6中断
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority=0x01; //抢占优先级1
NVIC_InitStructure.NVIC_IRQChannelSubPriority=0x03; //子优先级3
NVIC_InitStructure.NVIC_IRQChannelCmd=ENABLE;
NVIC_Init(&NVIC_InitStructure);
}
void BASE_TIME_IRQHandler(void)
{
if(TIM_GetITStatus(BASE_TIMER,TIM_IT_Update)==SET) //溢出中断
{
static char i = 0;
if(i == 0)
{
LED0(1);
i = 1;
}
else
{
i = 0;
LED0(0);
}
TIM_ClearITPendingBit(BASE_TIMER,TIM_IT_Update); //清除中断标志位
}
}
注意:这个TIM6非常特殊, 中断号和中断函数都其他的有点不一样.