TIM定时器编码器接口实现编码器计数
编码器接口引脚为定时器CH1,CH2
\
TIM编码器会在上升下降沿都计数,仅在TI1/TI2处计数,定时器值变化2,在TI1和TI2处均计数,计时器变化4
👇对应参数
#define TIM_ENCODERMODE_TI1 TIM_SMCR_SMS_0
#define TIM_ENCODERMODE_TI2 TIM_SMCR_SMS_1
#define TIM_ENCODERMODE_TI12 (TIM_SMCR_SMS_1 | TIM_SMCR_SMS_0)
👇将TIM2配置为编码器模式
/*使用TIM2计时器的编码器接口实现编码器计数*/
void Encoder_TIM2_Init(void)
{
/*TIM2编码器接口配置PA0,PA1*/
__HAL_RCC_GPIOA_CLK_ENABLE();
GPIO_InitTypeDef GPIO_Init_Struct;
GPIO_Init_Struct.Pin = GPIO_PIN_0 | GPIO_PIN_1;
GPIO_Init_Struct.Mode = GPIO_MODE_AF_OD;
GPIO_Init_Struct.Pull = GPIO_NOPULL;
GPIO_Init_Struct.Speed = GPIO_SPEED_FREQ_MEDIUM;
GPIO_Init_Struct.Alternate = GPIO_AF1_TIM2;
HAL_GPIO_Init(GPIOA,&GPIO_Init_Struct);
/*配置清零中断*/
GPIO_Init_Struct.Pin = GPIO_PIN_4;
GPIO_Init_Struct.Mode = GPIO_MODE_IT_FALLING;
GPIO_Init_Struct.Pull = GPIO_NOPULL;
GPIO_Init_Struct.Speed = GPIO_SPEED_FREQ_MEDIUM;
HAL_GPIO_Init(GPIOA,&GPIO_Init_Struct);
HAL_NVIC_SetPriority(EXTI4_IRQn,2,3);
HAL_NVIC_EnableIRQ(EXTI4_IRQn);
/*配置时钟TIM2为Encoder模式*/
__HAL_RCC_TIM2_CLK_ENABLE();
HAL_TIM_Encoder_DeInit(&h_TIM2);
h_TIM2.Instance = TIM2;
h_TIM2.Init.Prescaler = 1-1;
h_TIM2.Init.CounterMode = TIM_COUNTERMODE_UP;
h_TIM2.Init.Period = 65536-1;
h_TIM2.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
h_TIM2.Init.RepetitionCounter = 0;
h_TIM2.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;
Encoder_Init_Struct.EncoderMode = TIM_ENCODERMODE_TI1;
Encoder_Init_Struct.IC1Polarity = TIM_ICPOLARITY_RISING;
Encoder_Init_Struct.IC1Selection = TIM_ICSELECTION_DIRECTTI;
Encoder_Init_Struct.IC1Prescaler = TIM_ICPSC_DIV1;
Encoder_Init_Struct.IC1Filter = 0x0;
Encoder_Init_Struct.IC2Polarity = TIM_ICPOLARITY_FALLING;
Encoder_Init_Struct.IC2Selection = TIM_ICSELECTION_DIRECTTI;
Encoder_Init_Struct.IC2Prescaler = TIM_ICPSC_DIV1;
Encoder_Init_Struct.IC2Filter = 0x0;
HAL_TIM_Encoder_Init(&h_TIM2,&Encoder_Init_Struct);
HAL_TIM_Encoder_Start(&h_TIM2,TIM_CHANNEL_ALL);
}
👇旋转编码器改变定时器计数值,正转递增,反转递减