基本方法
1.设置TIM2 CH1为输入捕获功能;
2.设置上升沿捕获;
3.使能TIM2 CH1捕获功能;
4.捕获到上升沿后,存入capture_buf[0],改为捕获下降沿;
5.捕获到下降沿后,存入capture_buf[1],改为捕获上升沿;
6.捕获到上升沿后,存入capture_buf[2],关闭TIM2 CH1捕获功能;
7.计算:capture_buf[2] - capture_buf[0]就是周期,capture_buf[1] - capture_buf[0]就是高电平所占时间。
时钟配置:
引脚看是否需要上拉
做项目中的一个例子:
/** * 函数功能: TIM_IC配置 * 输入参数: value * 返 回 值: 无 * 说 明: 无 */ void user_ic_config(uint16_t value) { TIM_IC_InitTypeDef sConfigIC; if(value != 0) //1 { sConfigIC.ICPolarity = TIM_INPUTCHANNELPOLARITY_RISING;//上升沿 } else//0 { sConfigIC.ICPolarity = TIM_INPUTCHANNELPOLARITY_FALLING; //下降沿 } sConfigIC.ICSelection = TIM_ICSELECTION_DIRECTTI; sConfigIC.ICPrescaler = TIM_ICPSC_DIV1; sConfigIC.ICFilter = 0; HAL_TIM_IC_ConfigChannel(&htim2, &sConfigIC, TIM_CHANNEL_1); } /** * 函数功能: TIM_IC回调函数 * 输入参数: htim * 返 回 值: 无 * 说 明: 得到转速 */ void HAL_TIM_IC_CaptureCallback(TIM_HandleTypeDef *htim) { static uint32_t uwICValue; static uint32_t last_uwICValue; uint32_t uwDiffCapture; if ( ((htim->Channel == HAL_TIM_ACTIVE_CHANNEL_3)||(htim->Channel== HAL_TIM_ACTIVE_CHANNEL_4)) && (htim->Instance == TIM3) ) { pulseCntr++; last_uwICValue = uwICValue; uwICValue = HAL_TIM_ReadCapturedValue(htim, TIM_CHANNEL_3); if(HAL_TIM_IC_Start_IT(htim, TIM_CHANNEL_3) != HAL_OK) //开启定时器中断 { } if (uwICValue > last_uwICValue) { uwDiffCapture = (uwICValue - last_uwICValue); //脉冲宽度为前后两个周期相减 } else if (uwICValue < last_uwICValue) //若超值 { /* 0xFFFF is max TIM2_CCRx value */ uwDiffCapture = ((0xFFFF - last_uwICValue) + uwICValue) + 1; } if(uwDiffCapture < 0x10000) { middleCapture = uwDiffCapture; //脉冲宽度 } pulsein_flag = 1; // 捕捉到标记 } else if ( (htim->Channel == HAL_TIM_ACTIVE_CHANNEL_1) && (htim->Instance == TIM2) ) { if(uhCaptureIndex == 0) { // 第一个脉冲,检测的是上升沿 uwIC2Value1 = HAL_TIM_ReadCapturedValue(htim, TIM_CHANNEL_1); uhCaptureIndex = 1; user_ic_config(0); //下降 if(HAL_TIM_IC_Start_IT(htim, TIM_CHANNEL_1) != HAL_OK) //中断 { } } else if(uhCaptureIndex == 1) { uwIC2Value2 = HAL_TIM_ReadCapturedValue(htim, TIM_CHANNEL_1); uhCaptureIndex = 0; user_ic_config(1);//上升 if(HAL_TIM_IC_Start_IT(htim, TIM_CHANNEL_1) != HAL_OK) { } /* Capture computation */ if (uwIC2Value2 > uwIC2Value1) { uwDiffCapture = (uwIC2Value2 - uwIC2Value1); //脉冲宽度 } else if (uwIC2Value2 < uwIC2Value1) { /* 0xFFFF is max TIM2_CCRx value */ uwDiffCapture = ((40000 - uwIC2Value1) + uwIC2Value2) + 1; } RCin = uwDiffCapture/2; //删除 } } } 应用: 1.脉冲时间测量 2.电容按键使用