TIM-计时器学习笔记

当前我使用的STM32F407上有14个定时器(TIM1-TIM14)

确定计时器总线:
APB2 TIM 1 TIM8(高级) TIM 9 TIM 10 TIM 11 -----》168MHz
APB1 TIM6 TIM7(基本) TIM2 TIM3 TIM4 TIM5 TIM12 TIM13 TIM14 -----》84MHz
编写代码:
1) 开启计数器时钟
2) 初始化计数器
3) 开启计数器中断
4) 初始化NVIC
5) 开始计时
6) 编写中断触发函数
部分关键代码:
头文件:
#ifndef __TIM_H
#define __TIM_H
//头文件
#include “stm32f4xx.h” //这个头文件一定要留
//函数声明
void TIM3_Init(uint32_t Period,uint16_t Prescaler);
#endif
源文件:

#include “tim.h”
void TIM3_Init(uint32_t Period,uint16_t Prescaler)
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructrue;
NVIC_InitTypeDef NVIC_InitStructrue;
//开启计时器时钟 RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE); //初始化计时器 //TIM_TimeBaseInitStructrue.TIM_ClockDivision TIM_TimeBaseInitStructrue.TIM_CounterMode = TIM_CounterMode_Up; //计数模式 递增 TIM_TimeBaseInitStructrue.TIM_Period = Period-1; //计数周期 计时多久 TIM_TimeBaseInitStructrue.TIM_Prescaler = (Prescaler-1); //分频值 84MHz/(84-1+1)1usTIM_TimeBaseInit(TIM3, &TIM_TimeBaseInitStructrue); //开启计时中断 TIM_ITConfig(TIM3,TIM_IT_Update, ENABLE); //初始化NVIC NVIC_InitStructrue.NVIC_IRQChannel = TIM3_IRQn; NVIC_InitStructrue.NVIC_IRQChannelCmd = ENABLE; NVIC_InitStructrue.NVIC_IRQChannelPreemptionPriority = 1; NVIC_InitStructrue.NVIC_IRQChannelSubPriority = 1; NVIC_Init(&NVIC_InitStructrue); //开始计时TIM_Cmd(TIM3,DISABLE); 结束计时 //TIM_Cmd(TIM3,ENABLE);

【TIM-计时器学习笔记】}
//编写中断触发函数
uint16_t count;
void TIM3_IRQHandler(void)
{
if(TIM_GetFlagStatus(TIM3,TIM_FLAG_Update)!=RESET)
{
//清中断
TIM_ClearITPendingBit(TIM3, TIM_IT_Update);
count++;
}
}

    推荐阅读