stm32f103zet6 tim3通道1输入捕获完整代码,不使用hal库
时间: 2023-07-15 18:12:23 浏览: 118
好的,以下是STM32F103ZET6 TIM3通道1输入捕获的完整代码,不使用HAL库:
```c
#include "stm32f10x.h"
uint16_t ICValue1 = 0;
uint16_t ICValue2 = 0;
uint16_t Capture = 0;
void TIM3_IRQHandler(void)
{
if (TIM_GetITStatus(TIM3, TIM_IT_CC1) != RESET)
{
TIM_ClearITPendingBit(TIM3, TIM_IT_CC1);
if (Capture == 0)
{
ICValue1 = TIM_GetCapture1(TIM3);
Capture = 1;
}
else if (Capture == 1)
{
ICValue2 = TIM_GetCapture1(TIM3);
Capture = 0;
}
}
}
int main(void)
{
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
GPIO_Init(GPIOA, &GPIO_InitStructure);
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_TimeBaseStructure.TIM_Prescaler = 0;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseStructure.TIM_Period = 0xFFFF;
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseInit(TIM3, &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 = 0;
TIM_ICInit(TIM3, &TIM_ICInitStructure);
NVIC_InitTypeDef NVIC_InitStructure;
NVIC_InitStructure.NVIC_IRQChannel = TIM3_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
TIM_Cmd(TIM3, ENABLE);
TIM_ITConfig(TIM3, TIM_IT_CC1, ENABLE);
while (1)
{
if (Capture == 0)
{
printf("ICValue1: %d\n", ICValue1);
}
else if (Capture == 1)
{
printf("ICValue2: %d\n", ICValue2);
}
}
}
```
在这个例子中,我们使用了STM32F103ZET6的TIM3通道1输入捕获功能。我们首先使能了GPIOA和TIM3的时钟,并初始化了PA6为上拉输入模式。
然后,我们初始化了TIM3的计数器和输入捕获单元。在这里,我们将TIM3分频器设置为0,计数器模式设置为向上计数,周期设置为最大值,时钟分频器设置为不分频。我们还将通道1的输入捕获极性设置为上升沿触发,并且直接选择输入,输入分频器不分频,输入滤波器关闭。
接下来,我们初始化了TIM3的中断,并在主循环中读取输入捕获值,并将其打印到UART串口中。当捕获标志Capture为0时,我们打印ICValue1的值,当捕获标志Capture为1时,我们打印ICValue2的值。
最后,我们启用了TIM3和通道1的输入捕获中断,并在中断服务程序中读取输入捕获值,并将其存储在ICValue1和ICValue2中。注意,在中断服务程序中,我们使用了TIM_GetITStatus函数来检查输入捕获中断是否触发,并使用TIM_ClearITPendingBit函数来清除中断标志。
希望这个例子能够帮助你了解STM32F103ZET6 TIM3通道1输入捕获的使用。
阅读全文