基于STM32外部中断捕获低频频率的系统配置和代码书写
时间: 2024-01-24 15:02:00 浏览: 68
STM32外部中断捕获低频频率的系统配置和代码书写步骤如下:
1. 配置GPIO口为输入模式,对应的外部中断线路与GPIO口建立映射关系;
2. 配置外部中断线路触发方式为上升沿、下降沿或者双边沿触发;
3. 配置TIM计数器为定时器模式,设置定时器时钟频率和计数器最大值,使得定时器的计数时间足够长;
4. 配置TIM通道为输入捕获模式,选择对应的GPIO口和外部中断线路映射,设置输入捕获的触发方式;
5. 在外部中断的回调函数中,读取TIM计数器的当前值,计算捕获到的脉冲宽度和频率。
下面是代码实现的示例:
```c
#include "stm32f10x.h"
#define TIMx TIM2
#define TIMx_IRQn TIM2_IRQn
#define GPIO_Pin GPIO_Pin_0
#define GPIO_Port GPIOA
#define EXTI_Line EXTI_Line0
#define EXTI_PortSource EXTI_PortSourceGPIOA
#define EXTI_PinSource EXTI_PinSource0
volatile uint32_t g_pulseWidth = 0;
volatile uint32_t g_frequency = 0;
void TIM_Configuration(void)
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_ICInitTypeDef TIM_ICInitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
TIM_TimeBaseStructure.TIM_Period = 0xFFFF;
TIM_TimeBaseStructure.TIM_Prescaler = 71;
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIMx, &TIM_TimeBaseStructure);
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(TIMx, &TIM_ICInitStructure);
NVIC_InitStructure.NVIC_IRQChannel = TIMx_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
TIM_Cmd(TIMx, ENABLE);
TIM_ITConfig(TIMx, TIM_IT_CC1, ENABLE);
}
void EXTI_Configuration(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
EXTI_InitTypeDef EXTI_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(GPIO_Port, &GPIO_InitStructure);
EXTI_InitStructure.EXTI_Line = EXTI_Line;
EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt;
EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Rising_Falling;
EXTI_InitStructure.EXTI_LineCmd = ENABLE;
EXTI_Init(&EXTI_InitStructure);
NVIC_InitStructure.NVIC_IRQChannel = EXTI0_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
}
void EXTI0_IRQHandler(void)
{
if (EXTI_GetITStatus(EXTI_Line) != RESET)
{
g_pulseWidth = TIM_GetCapture1(TIMx);
g_frequency = SystemCoreClock / (TIMx->PSC + 1) / g_pulseWidth;
EXTI_ClearITPendingBit(EXTI_Line);
}
}
int main(void)
{
SystemInit();
TIM_Configuration();
EXTI_Configuration();
while (1)
{
// do something
}
}
```
在这个例子中,我们使用了TIM2的通道1作为输入捕获通道,对应的GPIO口为PA0。TIM2被配置为定时器模式,时钟频率为72MHz,计数器最大值为0xFFFF。在外部中断的回调函数中,计算捕获到的脉冲宽度和频率,然后将它们保存在全局变量中。注意,在计算频率时,需要除以脉冲宽度,再除以2,因为每个脉冲包含了两个边沿。
阅读全文