'Implementing a single press, long press and a double press function in HAL for STM32

I'm trying to implement a single press, double press and long press function to perform different functions. So far I've understood the logic for a single press and long press but I cant figure out how to detect a double press. As for the code, I've implemented the single press and long press using a counter but the code only stays on the first if condition.

          bool single_press = false;
      bool long_press = false;

      if (HAL_GPIO_ReadPin(GPIOC, GPIO_PIN_13))
      {

          HAL_TIM_Base_Start(&htim2);
          if ((TIM2->CNT == 20) && (HAL_GPIO_ReadPin(GPIOC, GPIO_PIN_13)))
          {
              single_press = true;
              long_press = false;
          }
          else if ((TIM2->CNT == 799) && (HAL_GPIO_ReadPin(GPIOC, GPIO_PIN_13)))
          {
              single_press = true;
              long_press = true;
          }
          HAL_TIM_Base_Stop(&htim2);
      }

      if (single_press == true && long_press == false)
      {
          HAL_GPIO_WritePin(GPIOB, GPIO_PIN_0, 1);
          HAL_Delay(1000);
          HAL_GPIO_WritePin(GPIOB, GPIO_PIN_0, 0);
      }
      else if (single_press == true && long_press == true)
      {
          HAL_GPIO_WritePin(GPIOB, GPIO_PIN_7, 1);
          HAL_Delay(1000);
          HAL_GPIO_WritePin(GPIOB, GPIO_PIN_7, 0);
      }
  }

I'm trying to implement a case where if I press the key for 20 ms (single press) PB0 will go high for a second and if I press the key for 800 ms PB7 will go high for a second. However, on running the program, when I press the button, PB0 goes high regardless of how long I hold the button and PB7 stays low. So I guess I have two questions:

  • How can I edit my code such that for a single press PB0 goes high and for a long press PB7 goes high?
  • How would one implement a double press function?

Thanks!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source