一、通用定时器TIMx功能实现
添加stm32f10x_tim.c打开stm32f10x_conf.h文件,将45行/*#include
"stm32f10x_tim.h"*/两边注释符去掉
基本定时功能实现
1.配置RCC,使能TIMx
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2,ENABLE);
2.配置NVIC,设置优先级等
NVIC_InitTypeDefNVIC_InitStructure;
NVIC_InitStructure.NVIC_IRQChannel= TIM2_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
3.配置TIMx
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
//设置计数器溢出周期(周期系数-1)
TIM_TimeBaseStructure.TIM_Period= 35999;
//设置分频系数(分频系数-1)
TIM_TimeBaseStructure.TIM_Prescaler= 1999;
//设置计数方向
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);
//使能定时器中断
TIM_ITConfig(TIM2, TIM_IT_Update, ENABLE);
//使能定时器
TIM_Cmd(TIM2, ENABLE);
4.写中断钩子函数(或称为中断服务函数,在文件stm32f10x_it.c中,也可在其它文件中创建)
{
if (TIM_GetITStatus(TIM2,TIM_IT_Update) != RESET)
{
TIM_ClearITPendingBit(TIM2,TIM_IT_Update);
//input your code
}
}
例:用TIM定时器功能输出周期为20ms占峰比50%pwm信号
设置定时器2的定时周期为10um
定义全局变量num
预定义
#define GPIO0_OFFGPIO_ResetBits(GPIOA,GPIO_Pin_0)
#define GPIO0_ONGPIO_SetBits(GPIOA,GPIO_Pin_0)
void TIM2_IRQHandler(void)
{
if(TIM_GetITStatus(TIM2, TIM_IT_Update) != RESET)
{
TIM_ClearITPendingBit(TIM2,TIM_IT_Update);
num=(num+1)%2000;
if(num<1000)
GPIOA0_H;
elseGPIOA0_L;
}
TIM硬件产生pwm信号
首先要使能GPIO的AFIO时钟使
GPIO要设置为GPIO_Mode_AF_PP 复用推挽输出
RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO,ENABLE);
TIM_OCInitTypeDef TIM_OCInitStructure;
/* Output Compare Timing Modeconfiguration: Channel1 */
TIM_OCInitStructure.TIM_OCMode =
TIM_OCMode_PWM1;//定时模式
TIM_OCInitStructure.TIM_Pulse =100;//比较数和TIM_TimeBaseStructure.TIM_Period的值作比
TIM_OCInitStructure.TIM_OCPolarity
= TIM_OCPolarity_High;//TIM输出比较极性低
TIM_OCInitStructure.TIM_OutputState=TIM_OutputState_Enable;
TIM_OC2Init(TIM2,
&TIM_OCInitStructure);// 使能TIM2的通道2
//TIM_OC1PreloadConfig(TIM2,
TIM_OCPreload_Enable);//使能TIM2的通道1
TIM功能使用注意:
1.TIM_PrescalerConfig(TIM2,PrescalerValue, TIM_PSCReloadMode_Immediate);
和TIM_TimeBaseStructure.TIM_Prescaler = 9; 作用的是同一寄存器TIMx->PSC
2.定时器在使能后会启动,如果这个时候其它初始化还没完成,容易造成不可知的错误,所以在初始化的时候,是能定时器应该尽量放在最后