Search code examples
buttonembeddedstm32

How to toggle the LCD Back light when User button is pressed on STM32f407-disc1


I am little new to embedded, I want to toggle the LCD Backlight (16x2) when I press the blue button on STM32f407-disc1, but when i press it for an instant it turns off then again comes back. Am I missing some delay or do I need to do it other way.

void btn_Task(void *pvParameters)
{
    uint8_t lcd_on = 1;
    while(1){

        if(HAL_GPIO_ReadPin(GPIOA, BTN_PIN) && lcd_on)
        {
           HD44780_NoBacklight();
           lcd_on = 0;
        }
        else
        {
            HD44780_Backlight();
            lcd_on = 1;
        }
        vTaskDelay(pdMS_TO_TICKS(50));
    }
}

Desired result should be -

  1. It should not toggle on and off back light upon holding the button and register it as a click untill released.
  2. Once the switch is pressed back light should change its state for infinitely if not toggled again.

Is something wrong in the logic or some delay is missing to make sure user has released the button when processing the logic.


Solution

  • To realize the toggling effect, your task needs to detect the change of the button state. For this it needs to remember the state of the button during the previous loop.

    I'm assuming that the pin is low when the button is pressed. Otherwise, adjust the assignment.

    To take button bounce into account, the task delays each loop by 50ms. There is no need for "sophisticated" debouncing logic, as such a sample rate is low enough to "jump over" the bouncing of most buttons, and is at the same time fast enough for the users.

    void btn_Task(void *pvParameters)
    {
        bool is_lcd_on = false;
        bool was_button_pressed = false;
    
        for (;;) {
            bool is_button_pressed = !HAL_GPIO_ReadPin(GPIOA, BTN_PIN);
    
            if (is_button_pressed && !was_button_pressed) {
                is_lcd_on = !is_lcd_on;
                if (is_lcd_on) {
                    HD44780_Backlight();
                } else {
                    HD44780_NoBacklight();
                }
            }
            was_button_pressed = is_button_pressed;
    
            vTaskDelay(pdMS_TO_TICKS(50));
        }
    }