STM32 外部计数ETR计算频率
扫描二维码
随时随地手机看文章
STM32 外部计数ETR计算频率,测量100K频率,用定时器2定时250ms,定时器3PD2(TIM3_ETR)计数,计算公式f=n*t;
void Tim3_Configuration(void)
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_TimeBaseStructure.TIM_Prescaler = 0x00;
TIM_TimeBaseStructure.TIM_Period = 0xFFFF;
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure); // Time base configuration
TIM_ETRClockMode2Config(TIM3, TIM_ExtTRGPSC_OFF, TIM_ExtTRGPolarity_NonInverted, 0);
TIM_ITConfig(TIM3, TIM_IT_Update, ENABLE);
TIM_SetCounter(TIM3, 0);
TIM_Cmd(TIM3, ENABLE);
}
void Tim2_Config(void)
{
TIM_TimeBaseInitTypeDef TIM2_TimeBaseStructure;
NVIC_InitTypeDef NVIC_InitStructure;
TIM_DeInit(TIM2);
TIM2_TimeBaseStructure.TIM_Period =(2500-1);
TIM2_TimeBaseStructure.TIM_Prescaler = (7200-1);
TIM2_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM2_TimeBaseStructure.TIM_CounterMode =TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM2, &TIM2_TimeBaseStructure); // Time base configuration
TIM_ClearFlag(TIM2,TIM_FLAG_Update);
TIM_ITConfig(TIM2,TIM_IT_Update,ENABLE );
TIM_Cmd(TIM2, ENABLE);
NVIC_InitStructure.NVIC_IRQChannel = TIM2_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
}
void TIM2_IRQHandler(void)
{
if (TIM_GetITStatus(TIM2, TIM_IT_Update) != RESET)
{
TIM_ClearITPendingBit(TIM2, TIM_IT_Update);
CAPTURE=(u32)TIM_GetCounter(TIM3);
}
sum+=CAPTURE;
count++;
if(count==4)
{
Frequency=sum*4;//求频率公式F=n*t;这里求了4次的计数值,合起来是1S的频率
sum=0;
count=0;
}
TIM_SetCounter(TIM3,0);
}