stm32f103STM1 输入捕获测量频率 占空比 波长 代码
时间: 2023-09-08 20:10:22 浏览: 105
stm32标准库输入捕获测频率、占空比.rar
5星 · 资源好评率100%
以下是使用STM32F103微控制器进行输入捕获测量频率、占空比和波长的示例代码:
```c
#include "stm32f10x.h"
#define TIMER_PRESCALER 72
#define PULSE_PERIOD 2000 // 2ms
uint32_t pulse_start_time = 0;
uint32_t pulse_end_time = 0;
float frequency = 0;
float duty_cycle = 0;
float wavelength = 0;
void TIM2_IRQHandler(void)
{
if(TIM_GetITStatus(TIM2, TIM_IT_CC1) != RESET)
{
if(pulse_start_time == 0)
{
pulse_start_time = TIM_GetCapture1(TIM2);
}
else
{
pulse_end_time = TIM_GetCapture1(TIM2);
frequency = (float)TIMER_PRESCALER / (pulse_end_time - pulse_start_time);
duty_cycle = (float)(pulse_end_time - pulse_start_time) / PULSE_PERIOD * 100;
wavelength = frequency == 0 ? 0 : 1 / frequency;
pulse_start_time = 0;
pulse_end_time = 0;
}
TIM_ClearITPendingBit(TIM2, TIM_IT_CC1);
}
}
void TIM2_Configuration(void)
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
TIM_TimeBaseStructInit(&TIM_TimeBaseStructure);
TIM_TimeBaseStructure.TIM_Period = PULSE_PERIOD - 1;
TIM_TimeBaseStructure.TIM_Prescaler = TIMER_PRESCALER - 1;
TIM_TimeBaseStructure.TIM_ClockDivision = 0;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);
TIM_OCStructInit(&TIM_OCInitStructure);
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitStructure.TIM_Pulse = PULSE_PERIOD / 2 - 1;
TIM_OC1Init(TIM2, &TIM_OCInitStructure);
TIM_ITConfig(TIM2, TIM_IT_CC1, 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);
}
int main(void)
{
TIM2_Configuration();
while(1)
{
// Your code here
}
}
```
在这个示例代码中,我们将TIM2定时器配置为PWM输出模式,并启用输入捕获来捕获PWM脉冲的上升沿和下降沿时间。当捕获到下降沿时间时,我们可以计算出频率、占空比和波长,并将它们存储在相应的变量中。请注意,示例代码中的PWM周期为2ms,可以根据实际需求进行修改。
阅读全文