1. 程式人生 > >STM32F302CB使用HAL庫採集PWM頻率和佔空比

STM32F302CB使用HAL庫採集PWM頻率和佔空比

微控制器執行在36MHz,以TIM2CH2為輸入通道,做如下配置:


/* TIM2 init function 由CubeMX生成,定時器初始化*/
void MX_TIM2_Init(void)
{
    TIM_MasterConfigTypeDef sMasterConfig;
    TIM_IC_InitTypeDef sConfigIC;

    htim2.Instance = TIM2;
    htim2.Init.Prescaler = 36 - 1;
    htim2.Init.CounterMode = TIM_COUNTERMODE_UP;
    htim2.Init
.Period = 0xFFFF; htim2.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1; htim2.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE; if (HAL_TIM_IC_Init(&htim2) != HAL_OK) { _Error_Handler(__FILE__, __LINE__); } sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET; sMasterConfig.MasterSlaveMode
= TIM_MASTERSLAVEMODE_DISABLE; if (HAL_TIMEx_MasterConfigSynchronization(&htim2, &sMasterConfig) != HAL_OK) { _Error_Handler(__FILE__, __LINE__); } sConfigIC.ICPolarity = TIM_INPUTCHANNELPOLARITY_RISING; sConfigIC.ICSelection = TIM_ICSELECTION_DIRECTTI; sConfigIC.ICPrescaler
= TIM_ICPSC_DIV1; sConfigIC.ICFilter = 4 - 1; if (HAL_TIM_IC_ConfigChannel(&htim2, &sConfigIC, TIM_CHANNEL_4) != HAL_OK) { _Error_Handler(__FILE__, __LINE__); } }
/*引腳初始化*/
void HAL_TIM_MspPostInit(TIM_HandleTypeDef *timHandle)
{
    GPIO_InitTypeDef GPIO_InitStruct;
    if(timHandle->Instance == TIM3)
    {
        /* USER CODE BEGIN TIM3_MspPostInit 0 */

        /* USER CODE END TIM3_MspPostInit 0 */

        /**TIM3 GPIO Configuration
        PA4     ------> TIM3_CH2
        */
        GPIO_InitStruct.Pin = GPIO_PIN_4;
        GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
        GPIO_InitStruct.Pull = GPIO_NOPULL;
        GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_MEDIUM;
        GPIO_InitStruct.Alternate = GPIO_AF2_TIM3;
        HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);

        /* USER CODE BEGIN TIM3_MspPostInit 1 */

        /* USER CODE END TIM3_MspPostInit 1 */
    }
}
//全域性變數,臨時用
uint32_t captureVal;
uint32_t captureVal2;
/*
MX_TIM2_Init中配置TIM2的分頻係數是36,TIM2的系統時鐘是36M。因此每ms TIM2發生一次計數。
譬如固定的PWM輸入(100Hz,40%佔空比,預設電平低電平),採集到的captureVal是4000,captureVal2是10000
*/
void HAL_TIM_IC_CaptureCallback(TIM_HandleTypeDef *htim)
{
    if(htim == &htim2)
    {
        static bool bRising = true;

        if(bRising)
        {
            captureVal = HAL_TIM_ReadCapturedValue(&htim2, TIM_CHANNEL_4);

            TIM_RESET_CAPTUREPOLARITY(&htim2, TIM_CHANNEL_4);
            TIM_SET_CAPTUREPOLARITY(&htim2, TIM_CHANNEL_4, TIM_INPUTCHANNELPOLARITY_RISING);
        }
        else
        {
            captureVal2 = HAL_TIM_ReadCapturedValue(&htim2, TIM_CHANNEL_4);

            __HAL_TIM_SET_COUNTER(&htim2, 0);

            TIM_RESET_CAPTUREPOLARITY(&htim2, TIM_CHANNEL_4);
            TIM_SET_CAPTUREPOLARITY(&htim2, TIM_CHANNEL_4, TIM_INPUTCHANNELPOLARITY_FALLING);
        }

        bRising = bRising ? false : true;
    }
}

上面的程式碼裡,配置了定時器每秒計數1000000次。captureVal2的值是一個PWM週期內的定時器計數值,1000000/captureVal2得到的就是PWM頻率。captureVal是PWM訊號高電平時間內的定時器計數值,captureVal/captureVal2得到的就是PWM的佔空比。