使用stm32f103实现频率计设计。使用2个通用定时器,一个计时,另一个对外部信号计数,在oled上显示出计数值和频率值。并且将代码以及注释写下
时间: 2024-02-23 08:57:32 浏览: 90
好的,下面是使用STM32F103实现频率计的设计,代码注释已经加上了:
```c
#include "stm32f10x.h"
#include "oled.h"
#include "delay.h"
// 定义计时器
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_ICInitTypeDef TIM_ICInitStructure;
// 定义计数值和频率值
uint32_t IC2Value = 0;
uint32_t IC1Value = 0;
uint32_t CaptureNumber = 0;
uint32_t Capture = 0;
uint32_t TIM1Freq = 0;
int main(void)
{
// 初始化OLED屏幕
OLED_Init();
OLED_Clear();
// 初始化计时器2
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
TIM_TimeBaseStructure.TIM_Period = 0xFFFF;
TIM_TimeBaseStructure.TIM_Prescaler = 71;
TIM_TimeBaseStructure.TIM_ClockDivision = 0;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);
// 初始化计时器1
RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM1, ENABLE);
TIM_TimeBaseStructure.TIM_Period = 0xFFFF;
TIM_TimeBaseStructure.TIM_Prescaler = 71;
TIM_TimeBaseStructure.TIM_ClockDivision = 0;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM1, &TIM_TimeBaseStructure);
// 初始化输入捕获2
TIM_ICInitStructure.TIM_Channel = TIM_Channel_2;
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(TIM2, &TIM_ICInitStructure);
// 初始化输入捕获1
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);
// 开启输入捕获2中断
TIM_ITConfig(TIM2, TIM_IT_CC2, ENABLE);
// 开启计时器2和计时器1
TIM_Cmd(TIM2, ENABLE);
TIM_Cmd(TIM1, ENABLE);
while (1)
{
// 显示计数值和频率值
OLED_ShowString(0, 0, "Count: Hz:");
OLED_ShowNum(60, 0, CaptureNumber, 5, 16);
OLED_ShowNum(120, 0, TIM1Freq, 5, 16);
}
}
// 计数器中断服务程序
void TIM2_IRQHandler(void)
{
if (TIM_GetITStatus(TIM2, TIM_IT_CC2) == SET)
{
TIM_ClearITPendingBit(TIM2, TIM_IT_CC2);
// 获取计数值
IC2Value = TIM_GetCapture2(TIM2);
if (CaptureNumber == 0)
{
// 获取第一次计数的时间
Capture = IC2Value;
CaptureNumber = 1;
}
else if (CaptureNumber == 1)
{
// 计算出两次计数的时间差
TIM1Freq = SystemCoreClock / ((IC2Value - Capture + 1) * 2);
CaptureNumber = 0;
}
}
}
```
注:以上代码仅供参考,具体实现需要根据实际情况进行调整。
阅读全文