1.STM32之定时器TIM---第一部分(基本定时器)(功能最强大结构最复杂的一个外设)(实验基本定时功能)-----定时器定时中断(利用内部时钟72M)
定时器TIM是STM32外设中功能最强大结构最复杂的一个外设!Whappy
STM32F103C8T6总共由一个高级定时器3个通用定时器
#include "stm32f10x.h" // Device header
#include "Delay.h"
#include "OLED.h"
#include "Timer.h"
uint16_t Num;
int main(void)
{
OLED_Init();
Timer_Init();
OLED_ShowString(1, 4, "Hi,Boy!");
OLED_ShowString(2, 1, "Num:");
while (1)
{
OLED_ShowNum(2,5,Num,5);
}
}
void TIM2_IRQHandler(void)
{
if(TIM_GetITStatus(TIM2,TIM_IT_Update) == SET)//检查一下中断标志位
{
//用户代码
Num++;
TIM_ClearITPendingBit(TIM2, TIM_IT_Update); //清除中断标志位
}
}
#include "stm32f10x.h" // Device header
//定时器初始化
void Timer_Init(void)
{
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2,ENABLE); //(1)开启TIM2的时钟
TIM_InternalClockConfig(TIM2);//(2)开启系统内部时钟
//(3)配置时基单元
TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure;
TIM_TimeBaseInitStructure.TIM_ClockDivision = TIM_CKD_DIV1 ;
TIM_TimeBaseInitStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInitStructure.TIM_Period = 10000-1;
TIM_TimeBaseInitStructure.TIM_Prescaler = 7200-1;
TIM_TimeBaseInitStructure.TIM_RepetitionCounter = 0;
TIM_TimeBaseInit(TIM2,&TIM_TimeBaseInitStructure);
TIM_ITConfig(TIM2,TIM_IT_Update,ENABLE);//(4)使能更新中断
//(5)配置NVIC
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
NVIC_InitTypeDef NVIC_InitStructure;
NVIC_InitStructure.NVIC_IRQChannel = TIM2_IRQn; //中断通道
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 2;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;
NVIC_Init(&NVIC_InitStructure);
//(5)启动定时器
TIM_Cmd(TIM2,ENABLE);
}
//定时器中断入口(在启动文件里找)
/*
void TIM2_IRQHandler(void)
{
if(TIM_GetITStatus(TIM12,TIM_IT_Update) == SET)//检查一下中断标志位
{
//用户代码
Num++;
TIM_ClearITPendingBit(TIM2,TIM_IT_Update); //清除中断标志位
}
}
*/
总结:配置一下最简单的内部时钟触发定时器计数,5步走,就可以完成配置(从代码中参考定时器中断基本结构图进行配置)