1. 程式人生 > >[STM32F103]PWM輸入捕獲配置

[STM32F103]PWM輸入捕獲配置

handler channel def oid cmd 配置 time stm32 初始

l 初始化定時器和通道對應IO的時鐘。

l 初始化IO口,模式為輸入:

  GPIO_Init();

GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPD; //PA0 輸入

l 初始化定時器ARR,PSC

  TIM_TimeBaseInit();

l 初始化輸入捕獲通道

  TIM_ICInit();

l 如果要開啟捕獲中斷,

  TIM_ITConfig();

  NVIC_Init();

l 使能定時器:

  TIM_Cmd();

l 編寫中斷服務函數:

  TIMx_IRQHandler();

l 源碼:

u8 TIM5CH1_CAPTURE_STA;
u16 TIM5CH1_CAPTURE_VAL;
void TIM5_Cap_Init(u16 arr, u16 psc) { GPIO_InitTypeDef GPIO_InitStructure; TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure; NVIC_InitTypeDef NVIC_InitStructure; TIM_ICInitTypeDef TIM_ICInitStructure; RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM5, ENABLE); RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE); GPIO_InitStructure.GPIO_Pin
= GPIO_Pin_0; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPD; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_Init(GPIOA, &GPIO_InitStructure); TIM_TimeBaseStructure.TIM_Period = arr; TIM_TimeBaseStructure.TIM_Prescaler = psc; TIM_TimeBaseStructure.TIM_ClockDivision
= TIM_CKD_DIV1; TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; TIM_TimeBaseInit(TIM5, &TIM_TimeBaseStructure); //捕獲通道設置 TIM_ICInitStructure.TIM_Channel = TIM_Channel_1; TIM_ICInitStructure.TIM_ICPolarity = TIM_ICPolarity_Rising; TIM_ICInitStructure.TIM_ICSelection = TIM_ICSelection_DirectTI; TIM_ICInitStructure.TIM_ICPrescaler = TIM_ICPSC_DIV1; TIM_ICInitStructure.TIM_ICFilter = 0x00; TIM_ICInit(TIM5, &TIM_ICInitStructure); NVIC_InitStructure.NVIC_IRQChannel = TIM5_IRQn; NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 2; NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0; NVIC_Init(&NVIC_InitStructure); TIM_ITConfig(TIM5, TIM_IT_Update|TIM_IT_CC1,ENABLE); TIM_Cmd(TIM5, ENABLE); } void TIM5_IRQHandler() { if((TIM5CH1_CAPTURE_STA & 0x80) == 0) { if(TIM_GetITStatus(TIM5, TIM_IT_Update) != RESET) { if(TIM5CH1_CAPTURE_STA & 0x40) { if((TIM5CH1_CAPTURE_STA & 0x3F) == 0x3F) { TIM5CH1_CAPTURE_STA |= 0x80; TIM5CH1_CAPTURE_VAL = 0xffff; } else { TIM5CH1_CAPTURE_STA++; } } } if(TIM_GetITStatus(TIM5, TIM_IT_CC1) != RESET) { if(TIM5CH1_CAPTURE_STA & 0x40) { TIM5CH1_CAPTURE_STA |= 0x80; TIM5CH1_CAPTURE_VAL = TIM_GetCapture1(TIM5); TIM_OC1PolarityConfig(TIM5, TIM_ICPolarity_Rising); } else { TIM5CH1_CAPTURE_STA = 0; TIM5CH1_CAPTURE_VAL = 0; TIM_SetCounter(TIM5, 0); TIM5CH1_CAPTURE_STA |= 0x40; TIM_OC1PreloadConfig(TIM5, TIM_ICPolarity_Falling); } } } TIM_ClearITPendingBit(TIM5, TIM_IT_CC1 | TIM_IT_Update); } //main.c u32 temp = 0; delay_init(); NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2); TIM5_Cap_Init(0xffff,72-1); uart_init(115200); while(1) { delay_ms(10); if(TIM5CH1_CAPTURE_STA & 0x80) { temp = TIM5CH1_CAPTURE_STA & 0x3f; temp *= 65536; temp += TIM5CH1_CAPTURE_VAL; printf("High:%d us\r\n",temp); TIM5CH1_CAPTURE_STA = 0; } }

[STM32F103]PWM輸入捕獲配置