一、初始化过程
/***********************************************************************
利用TIM4定时器作为计时,每个0.1秒处理一次数据
计算周期的公式为: psc/72*period/1000000 (单位为秒)
************************************************************************/
-
void TIM2_Config(void)
-
{
-
TIM_TimeBaseInitTypeDef TIM_timeBaseStucture;
-
TIM_OCInitTypeDef TIM_OCInitStructure;
-
-
u16 period = 1000; //设置PWM周期值(ARR值)
-
u16 pluse = 5000; //设置PWM脉冲宽度值(CRR值)
-
-
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM4, ENABLE); //使能TIM4时钟
-
-
TIM_DeInit(TIM4); //重置TIM4
-
//配置TIM4时基
-
TIM_timeBaseStucture.TIM_ClockDivision = TIM_CKD_DIV1; //分频因子
-
TIM_timeBaseStucture.TIM_Prescaler = 7200-1; //预分频
-
TIM_timeBaseStucture.TIM_CounterMode = TIM_CounterMode_Up; //向上计数
-
TIM_timeBaseStucture.TIM_Period = period;
-
TIM_TimeBaseInit(TIM4, &TIM_timeBaseStucture);
-
-
//配置TIM通道1的PWM输出
-
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1; //PWM输出模式为PWM1
-
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High; //设置有效电平的极性
-
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable; //使能通道输出PWM
-
TIM_OCInitStructure.TIM_Pulse = pluse; //设置PWM的脉冲宽度值,即CRR值
-
TIM_OC1Init(TIM4, &TIM_OCInitStructure);
-
-
TIM_ARRPreloadConfig(TIM4, ENABLE); //使能TIM3的寄存器ARR的预装载功能,DISABLE时将会使改变ARR值时立即生效
-
TIM_OC1PreloadConfig(TIM4, TIM_OCPreload_Enable); //使能TIM3通道1的CCR的预装载功能,DISABLE时将回使改变CRR值时立即生效
-
-
//使能TIM4定时器
-
TIM_Cmd(TIM4, ENABLE);
-
-
TIM_ClearFlag(TIM4, TIM_FLAG_Update); //先清除定时器更新标志位,防止一开启就进入中断处理函数
-
-
TIM_ITConfig(TIM4, TIM_IT_Update,ENABLE);
-
NVIC_EnableIRQ(TIM4_IRQn);
-
-
}
二、TIM4中断函数
-
void TIM4_IRQHandler(void)
-
{
-
if(TIM_GetITStatus(TIM4,TIM_IT_Update)==SET)
-
{
-
printf("here happened TIM4 IRQ.\n");
-
TIM_ClearITPendingBit(TIM4,TIM_IT_Update);
-
}
-
-
}
阅读(1168) | 评论(0) | 转发(0) |