2023-10-16 12:34 PM - edited 2023-10-16 12:52 PM
Here my new code to use encoder with STM32
First search on datasheet 2 pins with TIMx_CH1 and TIMx_CH2.
In my case was a STM32F469 and I have used PC6 and Pc7 with TIM8_CH1 and TIM8_CH2.
After search in the file stm32f4xx_hal_gpio_ex.h the relative AFx for your TIMx.
#define GPIO_AF3_TIM8 ((uint8_t)0x03) /* TIM8 Alternate Function mapping */
.
TIM_HandleTypeDef htim8;
uint32_t TIM8_save_counter = 0;
void MX_TIM8_Init(void)
{
TIM_Encoder_InitTypeDef sConfig = {0};
TIM_MasterConfigTypeDef sMasterConfig = {0};
GPIO_InitTypeDef gpio_init_structure;
__HAL_RCC_GPIOC_CLK_ENABLE();
__TIM8_CLK_ENABLE();
gpio_init_structure.Pin = GPIO_PIN_6|GPIO_PIN_7;
gpio_init_structure.Mode = GPIO_MODE_AF_PP;
gpio_init_structure.Pull = GPIO_PULLUP;
gpio_init_structure.Speed = GPIO_SPEED_LOW;
gpio_init_structure.Alternate = GPIO_AF3_TIM8;
HAL_GPIO_Init(GPIOC, &gpio_init_structure);
htim8.Instance = TIM8;
htim8.Init.Prescaler = 0;
htim8.Init.CounterMode = TIM_COUNTERMODE_UP;
htim8.Init.Period = 65535;
htim8.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
htim8.Init.RepetitionCounter = 0;
htim8.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_ENABLE;
sConfig.EncoderMode = TIM_ENCODERMODE_TI12;
sConfig.IC1Polarity = TIM_ICPOLARITY_RISING;
sConfig.IC1Selection = TIM_ICSELECTION_DIRECTTI;
sConfig.IC1Prescaler = TIM_ICPSC_DIV1;
sConfig.IC1Filter = 10;
sConfig.IC2Polarity = TIM_ICPOLARITY_RISING;
sConfig.IC2Selection = TIM_ICSELECTION_DIRECTTI;
sConfig.IC2Prescaler = TIM_ICPSC_DIV1;
sConfig.IC2Filter = 0;
if (HAL_TIM_Encoder_Init(&htim8, &sConfig) != HAL_OK)
{
Error_Handler();
}
sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
if (HAL_TIMEx_MasterConfigSynchronization(&htim8, &sMasterConfig) != HAL_OK)
{
Error_Handler();
}
//HAL_TIM_Encoder_Start(&htim8, TIM_CHANNEL_ALL);
HAL_TIM_Encoder_Start(&htim8, TIM_CHANNEL_1|TIM_CHANNEL_2);
}
and in the main loop
if (TIM8->CNT != TIM8_save_counter)
{
if (TIM8_save_counter == 0 && TIM8->CNT == 65535)
buttonInUp();
else if (TIM8_save_counter == 65535 && TIM8->CNT == 0)
buttonInDown();
else if (TIM8_save_counter < TIM8->CNT)
buttonInDown();
else
buttonInUp();
TIM8_save_counter = TIM8->CNT;
}
2023-10-16 12:38 PM
What does the code do? To whom is this directed?