首页 > 解决方案 > STM32带编码器

问题描述

我正在使用连接到编码器到定时器 3 的 stwinkt1 板。我想在每次编码器计数为 300 时获得一个中断,所以中断中的代码是:

void  TIM3_IRQHandler(void){
    // do things here

    //reset the encoder so ill start counting again
    __HAL_TIM_SET_COUNTER(&encoderTimer, 0);
    //clear the interrupt
    HAL_TIM_IRQHandler(&encoderTimer);
}

但是无论我如何定义编码器,每个脉冲都会中断 - 这是无用的,并且会无缘无故地消耗 CPU。这就是我定义编码器并启动它的方式:

void Init_Encoder_TIM(void){
    TIM_Encoder_InitTypeDef Config = {0};
    TIM_MasterConfigTypeDef MasterConfig = {0};

    //define the encoder clock
    encoderTimer.Instance = TIM_ENCODER;
    encoderTimer.Init.Prescaler = 0;
    encoderTimer.Init.CounterMode = TIM_COUNTERMODE_UP;
    encoderTimer.Init.Period = 0xFFFF;
    encoderTimer.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
    encoderTimer.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;
    Config.EncoderMode = TIM_ENCODERMODE_TI1;
    Config.IC1Polarity = TIM_ICPOLARITY_RISING;
    Config.IC1Selection = TIM_ICSELECTION_DIRECTTI;
    Config.IC1Prescaler = TIM_ICPSC_DIV1;
    Config.IC1Filter = 0;
    Config.IC2Polarity = TIM_ICPOLARITY_RISING;
    Config.IC2Selection = TIM_ICSELECTION_DIRECTTI;
    Config.IC2Prescaler = TIM_ICPSC_DIV1;
    Config.IC2Filter = 0;
    if (HAL_TIM_Encoder_Init(&encoderTimer, &Config) != HAL_OK)
    {
        Error_Handler();
    }
    MasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
    MasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
    if (HAL_TIMEx_MasterConfigSynchronization(&encoderTimer, &MasterConfig) != HAL_OK)
    {
        Error_Handler();
    }
    HAL_TIM_Encoder_Start_IT(&encoderTimer, TIM_CHANNEL_ALL);
}

我试图将预分频器设置为 300 它不起作用。我试图将 Period 设置为 300 它也不起作用。我尝试将 CCR3 手动设置为 300 并激活中断通道,但它也不起作用。

要清楚 - 中断有效,我得到中断,但对于每个编码器脉冲而不是每 300 个脉冲。

希望你知道如何帮助我 Itay

标签: stm32encoderhal

解决方案


推荐阅读