STM32F1 的定时器非常多,由 2 个基本定时器(TIM6、TIM7)、4 个通用定时器(TIM2-TIM5)和 2 个高级定时器(TIM1、TIM8)组成。
1、定时器有哪些,以及对应有什么功能
(1)基本定时器:
功能最为简单,类似于 51 单片机内定时器。
(2)通用定时器:
是在基本定时器的基础上扩展而来,增加了输入捕获(可以测量输入信号的脉宽)与输出比较(产生输出波形)等功能。
(3)高级定时器:
是在通用定时器基础上扩展而来,增加了可编程死区互补输出、重复计数器、带刹车(断路)功能,这些功能主要针对工业电机控制方面。
2、通用定时器配置
#include "stm32f10x.h"
uint8_t time_flag = 0;
void LED_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;//定义结构体变量
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC,ENABLE);
GPIO_InitStructure.GPIO_Pin=GPIO_Pin_0; //选择你要设置的IO口
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_Out_PP; //设置推挽输出模式
GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz;//设置传输速率
GPIO_Init(GPIOC,&GPIO_InitStructure); /* 初始化GPIO */
GPIO_SetBits(GPIOC,GPIO_Pin_0); //将LED端口拉高,熄灭所有LED
}
void TIM4_Init(u16 per,u16 psc)
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM4,ENABLE); //使能TIM4时钟
TIM_TimeBaseInitStructure.TIM_Period=per; //自动装载值
TIM_TimeBaseInitStructure.TIM_Prescaler=psc; //分频系数
TIM_TimeBaseInitStructure.TIM_ClockDivision=TIM_CKD_DIV1; //时钟分频
TIM_TimeBaseInitStructure.TIM_CounterMode=TIM_CounterMode_Up; //设置向上计数模式
TIM_TimeBaseInit(TIM4,&TIM_TimeBaseInitStructure);
TIM_ITConfig(TIM4,TIM_IT_Update,ENABLE); //开启定时器中断
TIM_ClearITPendingBit(TIM4,TIM_IT_Update);
NVIC_InitStructure.NVIC_IRQChannel = TIM4_IRQn; //定时器中断通道
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority=2;//抢占优先级
NVIC_InitStructure.NVIC_IRQChannelSubPriority =3; //子优先级
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; //IRQ通道使能
NVIC_Init(&NVIC_InitStructure);
TIM_Cmd(TIM4,ENABLE); //使能定时器
}
// TIM4中断函数
void TIM4_IRQHandler(void)
{
if(TIM_GetITStatus(TIM4,TIM_IT_Update))
{
if(time_flag){
time_flag = 0x00;
}
else{
time_flag = 0xff;
}
}
TIM_ClearITPendingBit(TIM4,TIM_IT_Update);
}
int main( void )
{
LED_Init();
TIM4_Init(1000,36000-1); //定时500ms
while(1)
{
if( time_flag ){
GPIO_ResetBits(GPIOC,GPIO_Pin_0);
}
else{
GPIO_SetBits(GPIOC,GPIO_Pin_0);
}
}
}
3、测试验证程序,下载到板子会看到LED闪烁,程序正常。
--END--
相关文章









