void Timer_Init(void) { RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE); RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE); GPIO_InitTypeDef GPIO_InitStructure; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU; GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_Init(GPIOA, &GPIO_InitStructure); TIM_ETRClockMode2Config(TIM2, TIM_ExtTRGPSC_OFF, TIM_ExtTRGPolarity_NonInverted, 0x0F); TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure; TIM_TimeBaseInitStructure.TIM_ClockDivision = TIM_CKD_DIV1; TIM_TimeBaseInitStructure.TIM_CounterMode = TIM_CounterMode_Up; TIM_TimeBaseInitStructure.TIM_Period = 10 - 1; TIM_TimeBaseInitStructure.TIM_Prescaler = 1 - 1; TIM_TimeBaseInitStructure.TIM_RepetitionCounter = 0; TIM_TimeBaseInit(TIM2, &TIM_TimeBaseInitStructure); TIM_ClearFlag(TIM2, TIM_FLAG_Update); TIM_ITConfig(TIM2, TIM_IT_Update, ENABLE); NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2); NVIC_InitTypeDef NVIC_InitStructure; NVIC_InitStructure.NVIC_IRQChannel = TIM2_IRQn; NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 2; NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1; NVIC_Init(&NVIC_InitStructure); TIM_Cmd(TIM2, ENABLE); } uint16_t Timer_GetCounter(void) { return TIM_GetCounter(TIM2); }
时间: 2024-02-07 08:03:49 浏览: 182
在这段代码中,Timer_Init函数用于初始化定时器TIM2和GPIOA外设的时钟。首先,通过调用RCC_APB1PeriphClockCmd函数打开TIM2外设的时钟,然后通过调用RCC_APB2PeriphClockCmd函数打开GPIOA外设的时钟。接下来,使用GPIO_InitTypeDef结构体对GPIOA进行配置,设置GPIOA的模式为输入上拉模式,引脚为GPIO_Pin_0,速度为50MHz。然后,使用TIM_ETRClockMode2Config函数配置TIM2的外部时钟模式,设置时钟分频系数为TIM_ExtTRGPSC_OFF,外部时钟极性为TIM_ExtTRGPolarity_NonInverted,外部时钟滤波器值为0x0F。接着,使用TIM_TimeBaseInitTypeDef结构体对TIM2进行配置,设置时钟分频系数为TIM_CKD_DIV1,计数模式为向上计数模式,计数器周期为10-1,预分频器值为1-1,重复计数器值为0。然后,使用TIM_ClearFlag函数清除TIM2的更新标志位,使用TIM_ITConfig函数使能TIM2的更新中断。接下来,使用NVIC_InitTypeDef结构体对TIM2的中断进行配置,设置中断优先级组为NVIC_PriorityGroup_2,中断通道为TIM2_IRQn,使能中断,设置抢占优先级为2,子优先级为1。最后,使用TIM_Cmd函数使能TIM2定时器。
而Timer_GetCounter函数用于获取TIM2的计数器值,通过调用TIM_GetCounter函数获取TIM2的计数器值,并返回给调用者。
综上所述,Timer_Init函数用于初始化TIM2定时器和GPIOA外设的时钟,并对TIM2进行配置,使其能够按照设定的参数进行定时计数。而Timer_GetCounter函数用于获取TIM2的计数器值。
#### 引用[.reference_title]
- *1* *2* *3* [STM32的时钟控制RCC和外设定时器](https://blog.csdn.net/michaelchain/article/details/119627776)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control,239^v3^insert_chatgpt"}} ] [.reference_item]
[ .reference_list ]
阅读全文