STM32定时器3定时自定义定时时间函数
时间: 2023-10-23 17:11:52 浏览: 56
以下是用STM32定时器3定时自定义定时时间的函数:
```c
#include "stm32f10x.h"
void TIM3_Configuration(uint16_t period)
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStruct;
// 打开TIM3时钟
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
// 初始化TIM3
TIM_TimeBaseInitStruct.TIM_Prescaler = 72 - 1; // 设置预分频器
TIM_TimeBaseInitStruct.TIM_CounterMode = TIM_CounterMode_Up; // 向上计数模式
TIM_TimeBaseInitStruct.TIM_Period = period - 1; // 设置定时时间
TIM_TimeBaseInitStruct.TIM_ClockDivision = TIM_CKD_DIV1; // 时钟分割
TIM_TimeBaseInitStruct.TIM_RepetitionCounter = 0; // 重复计数器
TIM_TimeBaseInit(TIM3, &TIM_TimeBaseInitStruct);
// 开启TIM3中断
NVIC_InitTypeDef NVIC_InitStructure;
NVIC_InitStructure.NVIC_IRQChannel = TIM3_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
// 启动TIM3
TIM_Cmd(TIM3, ENABLE);
}
void TIM3_IRQHandler(void)
{
if (TIM_GetITStatus(TIM3, TIM_IT_Update) != RESET) {
// 在此处添加定时器中断处理代码
TIM_ClearITPendingBit(TIM3, TIM_IT_Update); // 清除中断标志位
}
}
```
使用方法:
```c
TIM3_Configuration(1000); // 设置定时时间为1000ms
```
注意事项:
- 本例中设置的预分频器为72,即将定时器时钟分频为72MHz / 72 = 1MHz;
- 本例中设置的定时时间为period - 1,可调整为所需的时间;
- 定时器中断处理函数中添加自定义的中断处理代码;
- 在使用定时器前,需要先开启相应定时器的时钟。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)