stm32f103 TIM1 输入捕获 测量频率 周期 占空比代码
时间: 2023-10-20 21:06:50 浏览: 93
stm32f103输入捕获得到占空比与周期
5星 · 资源好评率100%
下面是STM32F103 TIM1输入捕获测量频率,周期和占空比的代码示例:
1. 配置TIM1为输入捕获模式:
```c
TIM_ICInitTypeDef TIM_ICInitStructure;
TIM_ICInitStructure.TIM_Channel = TIM_Channel_1;
TIM_ICInitStructure.TIM_ICPolarity = TIM_ICPolarity_Rising;
TIM_ICInitStructure.TIM_ICSelection = TIM_ICSelection_DirectTI;
TIM_ICInitStructure.TIM_ICPrescaler = TIM_ICPSC_DIV1;
TIM_ICInitStructure.TIM_ICFilter = 0x0;
TIM_ICInit(TIM1, &TIM_ICInitStructure);
TIM_Cmd(TIM1, ENABLE);
```
2. 定义变量存储捕获的值:
```c
uint16_t IC1Value = 0;
uint16_t IC2Value = 0;
```
3. 在TIM1输入捕获中断处理函数中获取捕获的值:
```c
void TIM1_CC_IRQHandler(void)
{
if(TIM_GetITStatus(TIM1, TIM_IT_CC1) != RESET)
{
TIM_ClearITPendingBit(TIM1, TIM_IT_CC1);
IC1Value = TIM_GetCapture1(TIM1);
}
else if(TIM_GetITStatus(TIM1, TIM_IT_CC2) != RESET)
{
TIM_ClearITPendingBit(TIM1, TIM_IT_CC2);
IC2Value = TIM_GetCapture2(TIM1);
}
}
```
4. 计算测量值:
```c
uint32_t TIM1Freq = SystemCoreClock / (TIM_GetPrescaler(TIM1) + 1);
uint32_t TIM1Period = (IC2Value - IC1Value + 0xFFFF) % 0xFFFF;
float TIM1DutyCycle = 100.0 * (IC2Value - IC1Value) / TIM1Period;
```
其中,`SystemCoreClock`为系统时钟频率。
完整代码示例:
```c
#include "stm32f10x.h"
uint16_t IC1Value = 0;
uint16_t IC2Value = 0;
int main(void)
{
RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM1, ENABLE);
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_TimeBaseStructure.TIM_Period = 0xFFFF;
TIM_TimeBaseStructure.TIM_Prescaler = 0;
TIM_TimeBaseStructure.TIM_ClockDivision = 0;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM1, &TIM_TimeBaseStructure);
TIM_ICInitTypeDef TIM_ICInitStructure;
TIM_ICInitStructure.TIM_Channel = TIM_Channel_1;
TIM_ICInitStructure.TIM_ICPolarity = TIM_ICPolarity_Rising;
TIM_ICInitStructure.TIM_ICSelection = TIM_ICSelection_DirectTI;
TIM_ICInitStructure.TIM_ICPrescaler = TIM_ICPSC_DIV1;
TIM_ICInitStructure.TIM_ICFilter = 0x0;
TIM_ICInit(TIM1, &TIM_ICInitStructure);
TIM_ICInitStructure.TIM_Channel = TIM_Channel_2;
TIM_ICInitStructure.TIM_ICPolarity = TIM_ICPolarity_Falling;
TIM_ICInit(TIM1, &TIM_ICInitStructure);
NVIC_InitTypeDef NVIC_InitStructure;
NVIC_InitStructure.NVIC_IRQChannel = TIM1_CC_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
TIM_ITConfig(TIM1, TIM_IT_CC1 | TIM_IT_CC2, ENABLE);
TIM_Cmd(TIM1, ENABLE);
while(1);
}
void TIM1_CC_IRQHandler(void)
{
if(TIM_GetITStatus(TIM1, TIM_IT_CC1) != RESET)
{
TIM_ClearITPendingBit(TIM1, TIM_IT_CC1);
IC1Value = TIM_GetCapture1(TIM1);
}
else if(TIM_GetITStatus(TIM1, TIM_IT_CC2) != RESET)
{
TIM_ClearITPendingBit(TIM1, TIM_IT_CC2);
IC2Value = TIM_GetCapture2(TIM1);
}
uint32_t TIM1Freq = SystemCoreClock / (TIM_GetPrescaler(TIM1) + 1);
uint32_t TIM1Period = (IC2Value - IC1Value + 0xFFFF) % 0xFFFF;
float TIM1DutyCycle = 100.0 * (IC2Value - IC1Value) / TIM1Period;
}
```
阅读全文