I've been attempting to work with an encoder on my ARM STM32F0 chip and have been having 0 luck.
First I went down the InputCapture using the CaptureCallback and some subtraction but that produced almost random results. Since I found out there is an encoder library inside of the HAL code so I should just be able to slap that in and happy days. Example 1 2 3
I've implemented each of these different methods and they all cripple on the same fact. TIMx->CNT
does not return some counting register but instead returns the pin state. It's as if the HAL library is not properly configuring the Internal Counter but it's also possible I am just making a mistake. If someone could guide me I would greatly appreciate it. Below I pasted some of my config/examples so as to help show what I am doing.
Setup
Tim_ENCHandle.Instance = TIMENC;
Tim_ENCHandle.Init.Period = 0xFFFF;
Tim_ENCHandle.Init.CounterMode = TIM_COUNTERMODE_UP;
Tim_ENCHandle.Init.Prescaler = 0;
Tim_ENCHandle.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
encConfig.EncoderMode = TIM_ENCODERMODE_TI12;
encConfig.IC1Filter = 0x0F;
encConfig.IC1Polarity = TIM_INPUTCHANNELPOLARITY_RISING;
encConfig.IC1Prescaler = TIM_ICPSC_DIV1;
encConfig.IC1Selection = TIM_ICSELECTION_DIRECTTI;
encConfig.IC2Filter = 0x0F;
encConfig.IC2Polarity = TIM_INPUTCHANNELPOLARITY_FALLING;
encConfig.IC2Prescaler = TIM_ICPSC_DIV1;
encConfig.IC2Selection = TIM_ICSELECTION_DIRECTTI;
if (HAL_TIM_Encoder_Init(&Tim_ENCHandle, &encConfig) != HAL_OK) {
Error_Handler();
}
if(HAL_TIM_Encoder_Start_IT(&Tim_ENCHandle,TIM_CHANNEL_ALL)!=HAL_OK){
Error_Handler();
}
defines:
/* Definition for TIMENC clock resources */
#define TIMENC TIM2
#define TIMENC_CLK_ENABLE() __HAL_RCC_TIM2_CLK_ENABLE()
#define TIMENC_CHANNEL_GPIO_PORT() __HAL_RCC_GPIOA_CLK_ENABLE()
#define TIMENC_GPIO_PORT GPIOA
#define TIMENC_GPIO_PIN_CHANNEL1 GPIO_PIN_1
#define TIMENC_GPIO_AF_TIMx GPIO_AF2_TIM2
#define TIMENC_IRQn TIM2_IRQn
#define TIMENC_IRQHandler TIM2_IRQHandler
MSP:
void HAL_TIM_Encoder_MspInit(TIM_HandleTypeDef *htim) {
GPIO_InitTypeDef GPIO_InitStruct;
TIMENC_CLK_ENABLE();
TIMENC_CHANNEL_GPIO_PORT();
GPIO_InitStruct.Pin = GPIO_PIN_1 | GPIO_PIN_2;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Pull = GPIO_PULLUP;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
GPIO_InitStruct.Alternate = TIMENC_GPIO_AF_TIMx;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
HAL_NVIC_SetPriority(TIMENC_IRQn, 0, 1);
HAL_NVIC_EnableIRQ(TIMENC_IRQn);
}
Grab data which is only returning pin state
transmitBufferSize = snprintf((char *)aTxBuffer, 64, "cnt: %d\n\r", TIMENC->CNT);