输入捕获模式测频率、PWMI模式测频率占空比-****博客 参考这篇文章!
来利用一个GPIO的定时器的两个通道进行捕获占空比和频率,看出可以看出。TI1FP1和TI2FP2,计数值分别在CCR1和CCR2中取,
测周法
IC.c
#include "stm32f10x.h" // Device header
void IC_Init(void)
{
//开启时钟
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
//配置GPIO
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6; //GPIO_Pin_15;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
//开启时基单元
TIM_InternalClockConfig(TIM3);
TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure;
TIM_TimeBaseInitStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseInitStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInitStructure.TIM_Period = 65536 - 1; //ARR
TIM_TimeBaseInitStructure.TIM_Prescaler = 72 - 1; //PSC
TIM_TimeBaseInitStructure.TIM_RepetitionCounter = 0;
TIM_TimeBaseInit(TIM3, &TIM_TimeBaseInitStructure);
//初始化输入捕获单元
TIM_ICInitTypeDef TIM_ICInitStructure;
TIM_ICInitStructure.TIM_Channel = TIM_Channel_1; //选择通道一
TIM_ICInitStructure.TIM_ICFilter = 0xF; //选择滤波器
TIM_ICInitStructure.TIM_ICPolarity = TIM_ICPolarity_Rising;
TIM_ICInitStructure.TIM_ICPrescaler = TIM_ICPSC_DIV1; //不分频
TIM_ICInitStructure.TIM_ICSelection = TIM_ICSelection_DirectTI; //直连通道
TIM_ICInit(TIM3,&TIM_ICInitStructure);
//方式1 配置PWMI模式 自动选择通道2和下降沿触发、间接通道,与上相反
TIM_PWMIConfig(TIM3,&TIM_ICInitStructure);
//方式2
// TIM_ICInitStructure.TIM_Channel = TIM_Channel_2; //选择通道一
// TIM_ICInitStructure.TIM_ICFilter = 0xF; //选择滤波器
// TIM_ICInitStructure.TIM_ICPolarity = TIM_ICPolarity_Falling; //下降沿触发
// TIM_ICInitStructure.TIM_ICPrescaler = TIM_ICPSC_DIV1; //不分频
// TIM_ICInitStructure.TIM_ICSelection = TIM_ICSelection_IndirectTI; //间接通道
// TIM_ICInit(TIM3,&TIM_ICInitStructure);
//主从模式配置
TIM_SelectInputTrigger(TIM3,TIM_TS_TI1FP1); //触发源选择
TIM_SelectSlaveMode(TIM3,TIM_SlaveMode_Reset); //从模式配置
TIM_Cmd(TIM3,ENABLE); //启动定时器
}
uint16_t IC_GetFreq(void) //获取最新一个周期的频率值
{
return 1000000/ (TIM_GetCapture1(TIM3)+1);
}
uint16_t IC_GetDuty(void) //测占空比
{
return (TIM_GetCapture2(TIM3)+1) *100 / (TIM_GetCapture1(TIM3)+1) ;
}
main.c
#include "stm32f10x.h" // Device header
#include "Delay.h"
#include "OLED.h"
#include "PWM.h"
#include "IC.h"
uint8_t i;
int main(void)
{
OLED_Init();
PWM_Init();
IC_Init();
OLED_ShowString(1,1,"Freq:00000Hz");
OLED_ShowString(2,1,"Duty:000%");
PWM_SetPrescaler(7200-1); //Freq = 72M / (PSC+1) / (ARR+1)
PWM_SetCompare1(50); //Duty = CCR/ARR+1
while (1)
{
OLED_ShowNum(1,6,IC_GetFreq(),5);
OLED_ShowNum(2,6,IC_GetDuty(),3);
}
}