单片机通过外部中断测量上升沿数量测量方波频率
时间: 2023-09-26 11:07:31 浏览: 155
好的,下面是一份基于STM32单片机的代码,可以通过外部中断测量上升沿数量来计算方波信号的频率:
```c
#include "stm32f10x.h"
#define TIMx TIM2
#define TIMx_IRQn TIM2_IRQn
volatile uint32_t g_count = 0;
volatile uint32_t g_frequency = 0;
void TIMx_IRQHandler(void)
{
if (TIM_GetITStatus(TIMx, TIM_IT_Update) != RESET)
{
g_count = 0;
TIM_ClearITPendingBit(TIMx, TIM_IT_Update);
}
}
void EXTI9_5_IRQHandler(void)
{
if (EXTI_GetITStatus(EXTI_Line5) != RESET)
{
g_count++;
EXTI_ClearITPendingBit(EXTI_Line5);
}
}
void TIMx_Configuration(void)
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_DeInit(TIMx);
TIM_TimeBaseStructure.TIM_Prescaler = 71; // 定时器分频系数,时钟频率为72MHz,分频系数为71,则定时器时钟频率为1MHz
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseStructure.TIM_Period = 0xFFFF;
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseStructure.TIM_RepetitionCounter = 0;
TIM_TimeBaseInit(TIMx, &TIM_TimeBaseStructure);
TIM_ITConfig(TIMx, TIM_IT_Update, ENABLE);
NVIC_InitTypeDef NVIC_InitStructure;
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);
}
void EXTI_Configuration(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
EXTI_InitTypeDef EXTI_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_AFIO, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
GPIO_Init(GPIOA, &GPIO_InitStructure);
GPIO_EXTILineConfig(GPIO_PortSourceGPIOA, GPIO_PinSource5);
EXTI_InitStructure.EXTI_Line = EXTI_Line5;
EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt;
EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Rising;
EXTI_InitStructure.EXTI_LineCmd = ENABLE;
EXTI_Init(&EXTI_InitStructure);
NVIC_InitStructure.NVIC_IRQChannel = EXTI9_5_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
}
int main(void)
{
TIMx_Configuration();
EXTI_Configuration();
while (1)
{
g_frequency = TIM_GetCounter(TIMx) * 1000000 / (g_count * 72);
TIM_SetCounter(TIMx, 0);
}
}
```
代码中使用的是TIM2定时器和PA5引脚,需要根据实际情况进行修改。代码的核心部分是在中断服务程序中对计数器进行操作,并在主函数中根据计数器和定时器的配置计算出频率。
阅读全文