STM32F3-PWM输入捕获测量频率脉宽
扫描二维码
随时随地手机看文章
利用STM32的PWM输入捕获功能,可以测方波的占空比和(或)频率
使用时将相应的输入配置为对应定时器对应的复用功能,外部待测量波形从该引脚输入
再配置定时器输入捕获功能相应参数,选择主从模式,最后打开中断或者DMA读取测量数据
1. Enable TIM clock
2. Configure the TIM pins by configuring the corresponding GPIO pins
3. Fill the TIM_ICInitStruct
5. Call TIM_ICInit(TIMx, &TIM_ICInitStruct) ;. Call TIM_PWMIConfig(TIMx, &TIM_ICInitStruct) ;
6. Enable the NVIC or the DMA to read the measured frequency.
7. Enable the corresponding interrupt (or DMA request) to read the Captured value
8. Configure the slave mode controller in reset mode
9. Call the TIM_Cmd(ENABLE) function to enable the TIM counter.
10. Use TIM_GetCapturex(TIMx); to read the captured value.
代码:
#ifndef __PWM_INPUT_H
#define __PWM_INPUT_H
#include "main.h"
#define PWM_INPUT_TIM TIM3
#define PWM_INPUT_TIM_CLK RCC_APB1Periph_TIM3
#define PWM_INPUT_CHANNEL TIM_Channel_2
#define PWM_INPUT_PIN GPIO_Pin_4
#define PWM_INPUT_PORT GPIOA
#define PWM_INPUT_GPIOCLK RCC_AHBPeriph_GPIOA
#define PWM_INPUT_GPIOAF GPIO_AF_2
#define PWM_INPUT_PINSOURCE GPIO_PinSource4
void PWM_INPUT_Config(void);
void TIM3_IRQHandler(void);
#endif
//========================================================/
#include "PWM_Input.h"
volatile uint16_t IC2Value = 0;
volatile uint16_t DutyCycle = 0;
volatile uint32_t Frequency = 0;
void PWM_INPUT_Config(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
TIM_ICInitTypeDef TIM_ICInitStructure;
RCC_AHBPeriphClockCmd(PWM_INPUT_GPIOCLK,ENABLE);
RCC_APB1PeriphClockCmd(PWM_INPUT_TIM_CLK,ENABLE);
GPIO_InitStructure.GPIO_Pin = PWM_INPUT_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
GPIO_Init(PWM_INPUT_PORT, &GPIO_InitStructure);
GPIO_PinAFConfig(PWM_INPUT_PORT, PWM_INPUT_PINSOURCE, PWM_INPUT_GPIOAF);
NVIC_InitStructure.NVIC_IRQChannel = TIM3_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
TIM_ICInitStructure.TIM_Channel=PWM_INPUT_CHANNEL;
TIM_ICInitStructure.TIM_ICFilter=0x0;
TIM_ICInitStructure.TIM_ICPolarity=TIM_ICPolarity_Rising;
TIM_ICInitStructure.TIM_ICPrescaler=TIM_ICPSC_DIV1;
TIM_ICInitStructure.TIM_ICSelection=TIM_ICSelection_DirectTI;
TIM_PWMIConfig(PWM_INPUT_TIM,&TIM_ICInitStructure);
TIM_SelectInputTrigger(PWM_INPUT_TIM,TIM_TS_TI2FP2);
TIM_SelectSlaveMode(PWM_INPUT_TIM,TIM_SlaveMode_Reset);
TIM_SelectMasterSlaveMode(PWM_INPUT_TIM,TIM_MasterSlaveMode_Enable);
TIM_Cmd(PWM_INPUT_TIM,ENABLE);
TIM_ITConfig(PWM_INPUT_TIM,TIM_IT_CC2,ENABLE);
}
void TIM3_IRQHandler(void)
{
TIM_ClearITPendingBit(TIM3, TIM_IT_CC2);
IC2Value = TIM_GetCapture2(TIM3);
if (IC2Value != 0)
{
DutyCycle = (TIM_GetCapture1(TIM3) * 100) / IC2Value;
Frequency = 72000000 / IC2Value;
}
else
{
DutyCycle = 0;
Frequency = 0;
}
// printf("DutyCycle= %dn",DutyCycle);
// printf("Frequency= %dn",Frequency);
}