Skip to main content
Ciuffoly
Senior
March 27, 2021
Question

[SOLVED] --- Encoder very easy code ---

  • March 27, 2021
  • 1 reply
  • 636 views

Here the code to read encoder.

unsigned int Enc_dir;
unsigned int save_a = 0, save_b = 0;
 
 
 
void BSP_Encoder_Init()
{
 GPIO_InitTypeDef gpio_init_structure;
 
 __HAL_RCC_GPIOF_CLK_ENABLE();
 
 gpio_init_structure.Pin = GPIO_PIN_8;
 gpio_init_structure.Mode = GPIO_MODE_IT_RISING_FALLING;
 gpio_init_structure.Pull = GPIO_PULLUP;
 
 HAL_GPIO_Init(GPIOF, &gpio_init_structure);
 
 gpio_init_structure.Pin = GPIO_PIN_9;
 gpio_init_structure.Mode = GPIO_MODE_IT_RISING_FALLING;
 gpio_init_structure.Pull = GPIO_PULLUP;
 
 HAL_GPIO_Init(GPIOF, &gpio_init_structure);
 
 HAL_NVIC_SetPriority(EXTI9_5_IRQn, 0, 0);
 HAL_NVIC_EnableIRQ(EXTI9_5_IRQn);
}
 
void EXTI9_5_IRQHandler(void)
{
 uint8_t now_a;
 uint8_t now_b;
 
 now_a = HAL_GPIO_ReadPin(GPIOF, GPIO_PIN_8);
 now_b = HAL_GPIO_ReadPin(GPIOF, GPIO_PIN_9);
 
 if (!save_a & !save_b)
 {
	 if (now_a)
	 {
	 save_a = now_a;
	 Enc_dir = 2;
	 }
	 if (now_b)
	 {
	 save_b = now_b;
	 Enc_dir = 1;
	 }
 }
 if (save_a & !save_b)
 {
	 if (!now_a)
	 {
	 save_a = now_a;
	 Enc_dir = 1;
	 }
	 if (now_b && now_a)
	 {
	 save_b = now_b;
	 Enc_dir = 2;
	 }
 }
 if (save_a & save_b)
 {
	 if (!now_a)
	 {
	 save_a = now_a;
	 Enc_dir = 2;
	 }
	 if (!now_b)
	 {
	 save_b = now_b;
	 Enc_dir = 1;
	 }
 }
 if ((!save_a) & (save_b))
 {
	 if (now_a)
 {
	 save_a = now_a;
	 Enc_dir = 1;
	 }
	 if (!now_b)
 {
	 save_b = now_b;
	 Enc_dir = 2;
	 }
 }
 HAL_GPIO_EXTI_IRQHandler(GPIO_PIN_8);
 HAL_GPIO_EXTI_IRQHandler(GPIO_PIN_9);
}
 
 
......
 
	 if (Enc_dir > 0)
	 {
	 if (Enc_dir == 2)
	 buttonUpClicked();
	 else
	 	 buttonDownClicked();
 
	 	 Enc_dir = 0;
	 }
 
 

This topic has been closed for replies.

1 reply

waclawek.jan
Super User
March 27, 2021

I personally would run this in regular timer interrupt, unless your encoder is a "machine" one with guaranteed no bouncing on edges (i.e. not the hand-turned input).

JW