使用普通定时器2来产生中断,计数方式:增计数! 一、编程配置部分 1、首先进行中断配置,定时器中断肯定要配置的,代码如下:
[cpp] view plain copy
print?
- void TIM2_NVIC_Configuration(void)
- {
- NVIC_InitTypeDef NVIC_InitStructure;
-
- NVIC_PriorityGroupConfig(NVIC_PriorityGroup_0);
- NVIC_InitStructure.NVIC_IRQChannel = TIM2_IRQn;
- NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
- NVIC_InitStructure.NVIC_IRQChannelSubPriority = 3;
- NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
- NVIC_Init(&NVIC_InitStructure);
- }
这部分就不详述了 2、定时器的配置才是重点
[csharp] view plain copy
print?
- /*TIM_Period--1000 TIM_Prescaler--71 -->中断周期为1ms*/
- void TIM2_Configuration(void)
- {
- TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
- RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2 , ENABLE);
- TIM_DeInit(TIM2);
- TIM_TimeBaseStructure.TIM_Period=1000; /* 自动重装载寄存器周期的值(计数值) */
- /* 累计 TIM_Period个频率后产生一个更新或者中断 */
- TIM_TimeBaseStructure.TIM_Prescaler= (72 - 1); /* 时钟预分频数 72M/72 */
- TIM_TimeBaseStructure.TIM_ClockDivision=TIM_CKD_DIV1; /* 采样分频 */
- TIM_TimeBaseStructure.TIM_CounterMode=TIM_CounterMode_Up; <span style="white-space:pre"> </span>/* 向上计数模式 */
- TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);
- TIM_ClearFlag(TIM2, TIM_FLAG_Update); /* 清除溢出中断标志 */
- TIM_ITConfig(TIM2,TIM_IT_Update,ENABLE);
- TIM_Cmd(TIM2, ENABLE); <span style="white-space:pre"> </span>/* 开启时钟 */
- RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2 , DISABLE); /*先关闭等待使用*/
- }
还是一样,找到这个结构体
[csharp] view plain copy
print?
- TIM_TimeBaseInitTypeDef{
- uint16_t TIM_ClockDivision
- uint16_t TIM_CounterMode
- uint16_t TIM_Period
- uint16_t TIM_Prescaler
- uint8_t TIM_RepetitionCounter
- }
2、TIM_CounterMode用于设置计数模式
#define | | #define | | #define | | #define | | #define | | 3、TIM_Period
Specifies the period value to be loaded into the active Auto-Reload Register at the next update event. This parameter must be a number between 0x0000 and 0xFFFF. 就是一个重装值而已!Specifies the prescaler value used to divide the TIM clock. This parameter can be a number between 0x0000 and 0xFFFF
设置范围比较广,这里有一个计算公式 Specifies the repetition counter value. Each time the RCR downcounter reaches zero, an update event is generated and counting restarts from the RCR value (N) 这是在PWM里面用到的,这里可以不作设置 6、配置中断,清除中断标志位
[csharp] view plain copy
print?
- TIM_ClearFlag(TIM2, TIM_FLAG_Update); /* 清除溢出中断标志 */
- TIM_ITConfig(TIM2,TIM_IT_Update,ENABLE);
至此整个TIM2就配置完毕!不难得出,最后出来的结果就是:
/*TIM_Period--1000 TIM_Prescaler--71 -->中断周期为1ms*/ |