[HAL库学习之路]9.输入捕获

记录自己的STM32的HAL库的学习之路,不定期更新…

一、Pinout

[HAL库学习之路]9.输入捕获_第1张图片

二、Clock Configuration

[HAL库学习之路]9.输入捕获_第2张图片

三、Configuration

[HAL库学习之路]9.输入捕获_第3张图片
[HAL库学习之路]9.输入捕获_第4张图片
[HAL库学习之路]9.输入捕获_第5张图片

四、Generate Code

[HAL库学习之路]9.输入捕获_第6张图片

代码
计数频率为1MHz,捕获到高电平后改变为下降沿捕获,并设置标志位,定时器更新中断来计算高电平时长,高电平时间

T=N0XFFFFFFFF+captureVal
其中N为定时器溢出次数,captureVal为捕获时定时器的值,单位为us

int main(void)
{

  /* USER CODE BEGIN 1 */
    long long temp = 0;
  /* USER CODE END 1 */

  /* MCU Configuration----------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */
  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_TIM5_Init();
  MX_USART1_UART_Init();

  /* USER CODE BEGIN 2 */
    HAL_TIM_IC_Start_IT(&htim5, TIM_CHANNEL_1);
    __HAL_TIM_ENABLE_IT(&htim5, TIM_IT_UPDATE);
  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
  /* USER CODE END WHILE */

  /* USER CODE BEGIN 3 */
        HAL_Delay(10);
        if(captureStatus & 0x80)
        {
            temp = captureStatus & 0x3F;
            temp *= 0xFFFFFFFF;
            temp += captureVal;
            captureStatus = 0;
        }
  }
  /* USER CODE END 3 */

}
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{

    if((captureStatus & 0x80) == 0)
    {
        if(captureStatus & 0x40)
        {
            if((captureStatus & 0x3F) == 0x3F)
            {
                captureStatus |= 0x80;
                captureVal = 0xFFFFFFFF;
            }
            else 
                captureStatus++;
        }
    }

}

void HAL_TIM_IC_CaptureCallback(TIM_HandleTypeDef *htim)
{
    if((captureStatus & 0x80) == 0)
    {
        if(captureStatus & 0x40)
        {
            captureStatus |= 0x80;
            captureVal = HAL_TIM_ReadCapturedValue(&htim5, TIM_CHANNEL_1);
            TIM_RESET_CAPTUREPOLARITY(&htim5, TIM_CHANNEL_1);
            TIM_SET_CAPTUREPOLARITY(&htim5, TIM_CHANNEL_1, TIM_INPUTCHANNELPOLARITY_RISING);
        }
        else 
        {
            __HAL_TIM_DISABLE(&htim5);      
            captureStatus = 0;
            captureStatus |= 0x40;
            captureVal = 0;
            __HAL_TIM_SetCounter(&htim5, 0);
            TIM_RESET_CAPTUREPOLARITY(&htim5, TIM_CHANNEL_1);
            TIM_SET_CAPTUREPOLARITY(&htim5, TIM_CHANNEL_1, TIM_INPUTCHANNELPOLARITY_FALLING);
            __HAL_TIM_ENABLE(&htim5);
        }
    }   
}

你可能感兴趣的:(HAL库学习之路,库,stm32,HAL库)