基于stm32 f401RCT6芯片标准库定时器1产生50ms定时初始化
时间: 2023-11-03 19:16:03 浏览: 49
以下是基于stm32 f401RCT6芯片标准库定时器1产生50ms定时初始化的代码:
首先,需要在main函数中初始化定时器时钟,并设置定时器1的基本参数,如下所示:
```
#include "stm32f4xx.h"
#include "stm32f4xx_tim.h"
int main(void)
{
/* 初始化定时器时钟 */
RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM1, ENABLE);
/* 定时器1基本参数设置 */
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_TimeBaseStructure.TIM_Period = 50000 - 1; // 自动重载计数器值
TIM_TimeBaseStructure.TIM_Prescaler = 84 - 1; // 分频系数
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; // 计数器模式为向上计数
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1; // 时钟分割
TIM_TimeBaseInit(TIM1, &TIM_TimeBaseStructure);
/* 使能定时器1 */
TIM_Cmd(TIM1, ENABLE);
while (1)
{
/* 无限循环等待定时器1中断事件 */
}
}
```
接下来,需要在中断向量表中添加定时器1中断服务程序,并在该服务程序中添加相应的中断处理程序,如下所示:
```
void TIM1_UP_TIM10_IRQHandler(void)
{
if (TIM_GetITStatus(TIM1, TIM_IT_Update) != RESET)
{
/* 清除中断标志位 */
TIM_ClearITPendingBit(TIM1, TIM_IT_Update);
/* 在此添加需要执行的定时任务 */
}
}
```
最后,需要在main函数中使能定时器1中断,并启动定时器1的计数器,如下所示:
```
/* 使能定时器1中断 */
NVIC_InitTypeDef NVIC_InitStructure;
NVIC_InitStructure.NVIC_IRQChannel = TIM1_UP_TIM10_IRQn; // 中断通道为定时器1更新中断
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0; // 抢占优先级为0
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0; // 子优先级为0
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; // 使能中断
NVIC_Init(&NVIC_InitStructure);
/* 启动定时器1计数器 */
TIM_ITConfig(TIM1, TIM_IT_Update, ENABLE); // 使能定时器1更新中断
TIM_SetCounter(TIM1, 0); // 清空计数器
TIM_Cmd(TIM1, ENABLE); // 启动计数器
```
这样,就实现了基于stm32 f401RCT6芯片标准库定时器1产生50ms定时初始化。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![](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)