cancel
Showing results for 
Search instead for 
Did you mean: 

[SOLVED] -- very simple encoder ---

Here my simple code to use the encoder on STM32F746.

I have used the PI2 and PI3 of the STM32F746G-DISCO for input and volume control on an external DAC.

Probably someone could reduce the lines of code and obtain the same result.

unsigned int   Enc_dir;   << output direction up/down to use in the main() or in
                                                handleTickEvent() in case of TouchGFX graphical interface
                                                environment.
unsigned int  save_a = 0, save_b = 0;  << global variables
 
 
void EXTI2_IRQHandler(void)
{
    uint8_t now_a;
    uint8_t now_b;
 
 
    HAL_GPIO_EXTI_IRQHandler(GPIO_PIN_2);
 
    now_a = HAL_GPIO_ReadPin(GPIOI, GPIO_PIN_2);
    now_b = HAL_GPIO_ReadPin(GPIOI, GPIO_PIN_3);
 
 
    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;
	}
    }
}
 
void BSP_Encoder_Init()
{
  GPIO_InitTypeDef  gpio_init_structure;
 
  __HAL_RCC_GPIOI_CLK_ENABLE();
 
  gpio_init_structure.Pin = GPIO_PIN_2;
  gpio_init_structure.Mode = GPIO_MODE_IT_RISING_FALLING;
  gpio_init_structure.Pull = GPIO_PULLUP;
 
  HAL_GPIO_Init(GPIOI, &gpio_init_structure);
 
  HAL_NVIC_SetPriority(EXTI2_IRQn, 0, 0);
  HAL_NVIC_EnableIRQ(EXTI2_IRQn);
 
  gpio_init_structure.Pin = GPIO_PIN_3;
  gpio_init_structure.Mode = GPIO_MODE_INPUT;
  gpio_init_structure.Pull = GPIO_PULLUP;
 
  HAL_GPIO_Init(GPIOI, &gpio_init_structure);
}

0 REPLIES 0