一:实验目的 利用定时器实现1s计数,并在串口输出计数值。 这里我使用的是基通用定时器2.5完成的计数功能; 定时器介绍:TIMx 由一个 16 位可实时编程预分频器和一个 32 位计数方向可调的自动重装载计数器组成,可以为用户提供便捷的计数定时功能,计数器时钟由预分频器分频得到。通用定时器具有多种用途,如输入功能(测量输入信号的脉冲宽度、频率, PWM 输入等),输出功能( PWM 输出、单脉冲模式输出等)。 二:软件配置流程: 使能定时器时钟。 初始化定时器,配置ARR,PSC。 开启定时器中断,配置NVIC。 使能定时器。 编写中断服务函数。 软件代码: void TIM2_5_Configure(void) { NVIC_InitTypeDef NVIC_InitStruct; TIM_TimeBaseInitTypeDef TIM_TimeBaseStruct; RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE); TIM_TimeBaseStructInit(&TIM_TimeBaseStruct); TIM_TimeBaseStruct.TIM_Prescaler = (TIM_GetTIMxClock(TIM2) / 10000 - 1); TIM_TimeBaseStruct.TIM_CounterMode = TIM_CounterMode_Up; TIM_TimeBaseStruct.TIM_Period = (10000 - 1); TIM_TimeBaseStruct.TIM_ClockDivision = TIM_CKD_Div1; TIM_TimeBaseStruct.TIM_RepetitionCounter = 0; TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStruct); TIM_ITConfig(TIM2, TIM_IT_Update, ENABLE); NVIC_InitStruct.NVIC_IRQChannel = TIM2_IRQn; NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority = 0; NVIC_InitStruct.NVIC_IRQChannelSubPriority = 1; NVIC_InitStruct.NVIC_IRQChannelCmd = ENABLE; NVIC_Init(&NVIC_InitStruct); TIM_Cmd(TIM2, ENABLE); RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM5, ENABLE); TIM_TimeBaseStructInit(&TIM_TimeBaseStruct); TIM_TimeBaseStruct.TIM_Prescaler = (TIM_GetTIMxClock(TIM5) / 10000 - 1); TIM_TimeBaseStruct.TIM_CounterMode = TIM_CounterMode_Up; TIM_TimeBaseStruct.TIM_Period = (5000 - 1); TIM_TimeBaseStruct.TIM_ClockDivision = TIM_CKD_Div1; TIM_TimeBaseStruct.TIM_RepetitionCounter = 0; TIM_TimeBaseInit(TIM5, &TIM_TimeBaseStruct); TIM_ITConfig(TIM5, TIM_IT_Update, ENABLE); NVIC_InitStruct.NVIC_IRQChannel = TIM5_IRQn; NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority = 0; NVIC_InitStruct.NVIC_IRQChannelSubPriority = 1; NVIC_InitStruct.NVIC_IRQChannelCmd = ENABLE; NVIC_Init(&NVIC_InitStruct); TIM_Cmd(TIM5, ENABLE); } 中断函数处理部分: int temp1 = 0 ; void TIM2_IRQHandler(void) { if (RESET != TIM_GetITStatus(TIM2, TIM_IT_Update)) { PLATFORM_LED_Toggle(LED2); TIM_ClearITPendingBit(TIM2, TIM_IT_Update); temp1 ++ ; } } /*********************************************************************************************************************** * @brief This function handles TIM5 * @param none * @retval none *********************************************************************************************************************/ void TIM5_IRQHandler(void) { if (RESET != TIM_GetITStatus(TIM5, TIM_IT_Update)) { // PLATFORM_LED_Toggle(LED3); TIM_ClearITPendingBit(TIM5, TIM_IT_Update); } } 测试图片如下:
|