stm32gpio

How to code latch switch function using STM32?


I am looking a code to get the latch switch function using STM32. The below code which I have tried is working in stm32 but only a push button function without latch.

while (1)
{
      if(HAL_GPIO_ReadPin(GPIOC,GPIO_PIN_13)== GPIO_PIN_RESET )
      {
          HAL_GPIO_WritePin(GPIOA,GPIO_PIN_5,GPIO_PIN_SET);
      }
      else
      {
          HAL_GPIO_WritePin(GPIOA,GPIO_PIN_5,GPIO_PIN_RESET);       
      }         
} 

Can some one help me to make the GPIOA,GPIO_PIN_5 pin high always on the first press of the button and the GPIOA,GPIO_PIN_5 low always at the second press ?

The function will be similar as in the below video https://www.youtube.com/watch?v=zzWzSPdxA0U

Thank you all in advance.


Solution

  • There are several problems with the code. There is no memory function and you are reading the button at max speed.

    This is fixed by sleeping for a period of time to allow for human reaction speed and button noise. You also need a variable to store the previous state.

    while (1)
    {
          if(HAL_GPIO_ReadPin(GPIOC,GPIO_PIN_13)== GPIO_PIN_RESET )
          {
              static bool state = false;
              if(state == false)
              {
                  state = true;
                  HAL_GPIO_WritePin(GPIOA,GPIO_PIN_5,GPIO_PIN_SET);
              }
              else
              {
                  state = false
                  HAL_GPIO_WritePin(GPIOA,GPIO_PIN_5,GPIO_PIN_RESET);
              }
              while(HAL_GPIO_ReadPin(GPIOC,GPIO_PIN_13)== GPIO_PIN_RESET){} // wait for button to be released, otherwise it will keep toggling every 500ms 
          }
          delay_ms(500);
    } 
    

    This is C++ code as it uses bool. int with the values 1 and 0 can be used for C.

    What is done is a variable state is declared and kept in heap memory because of the static keyword. (Instead of stack memory which would be destroyed when the scope of the outer if statement is exited) It is initialized to false and then updated when you press the button.