stm32F103定时器2定时10s
时间: 2023-05-19 18:03:05 浏览: 117
stm32定时器
可以使用以下代码实现:
```
#include "stm32f10x.h"
void TIM2_IRQHandler(void)
{
if (TIM_GetITStatus(TIM2, TIM_IT_Update) != RESET)
{
// 定时器2中断处理代码
// ...
TIM_ClearITPendingBit(TIM2, TIM_IT_Update);
}
}
int main(void)
{
// 初始化定时器2
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_TimeBaseStructure.TIM_Period = 10000 - 1; // 定时10s
TIM_TimeBaseStructure.TIM_Prescaler = 7200 - 1; // 时钟频率为72MHz,分频7200,得到10kHz的计数频率
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);
// 使能定时器2中断
NVIC_InitTypeDef NVIC_InitStructure;
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);
TIM_ITConfig(TIM2, TIM_IT_Update, ENABLE);
// 启动定时器2
TIM_Cmd(TIM2, ENABLE);
while (1)
{
// 主循环代码
// ...
}
}
```
阅读全文