Encoder mode shows only 0 or the max ARR value. Does not increment.
I'm trying to simulate a quadrature encoder signal coming out of an automotive car seat motor. I don't have the motor but I do have the hall sensor used in it (Allegro A1221LLH). The Vout from the sensor is not accessible in the motor and its a 3-pin sensor converted to a 2-pin setup. Hence some hardware processing was needed to make it readable by the STM32F407. The good part is that it works and I see a nice square wave when I rotate a magnet over it (its not strictly quadrature since I have only one sensor for now).
I tried reading the count by configuring TIM2 in encoder mode. However I dont see the count increment. I see either 0 or the maximum ARR value (65535). What am I missing here? I've used the same count function with a standard optical encoder and that works fine. Here is the code:
typedef struct
{
uint16_t current_count; // variable that stores the current encoder count
uint16_t previous_count; // variable that stores the previous encoder count
uint16_t number_of_revs; // variable that stores the number of revs of the encoder
uint16_t total_count; // variable that stores the total encoder count
} Motor_Encoder;
Motor_Encoder M2;
uint16_t Get_Encoder_Count(Motor_Encoder *motor, TIM_HandleTypeDef *htim)
{
motor->current_count = __HAL_TIM_GET_COUNTER(htim);
motor->total_count = (motor->number_of_revs * __HAL_TIM_GET_AUTORELOAD(htim)) + motor->current_count;
motor->previous_count = motor->current_count;
if (motor->total_count < 0) motor->total_count = 0;
return motor->total_count;
}
int main(void)
{
HAL_Init();
MX_GPIO_Init();
MX_TIM2_Init();
__HAL_TIM_CLEAR_IT(&htim2, TIM_IT_UPDATE);
HAL_TIM_Base_Start_IT(&htim2); // Encoder M2
HAL_TIM_Encoder_Start(&htim2, TIM_CHANNEL_ALL);
while (1)
{
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
Get_Encoder_Count(&M2, &htim2);
HAL_Delay(1);
}
}
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
if (htim->Instance == TIM2)
{
__HAL_TIM_IS_TIM_COUNTING_DOWN(&htim2) ? M2.number_of_revs-- : M2.number_of_revs++;
if (M2.number_of_revs < 0) M2.number_of_revs = 0;
}
}