[esp32 + LVGL] Physical buttons control on-screen switches and LED flashing

Please add a picture description

1. Brief description

The button corresponding to IO0 controls the flashing of the IO2 LED. At the same time, the switch is closed when the LED is on, and the LED is flashing when the LED is off.
Why do this, because there is no touch screen in hand.

2. Implementation principle

First of all, we need to understand the principle of switch closure. For a touch screen, when you touch the switch, a click event will be triggered, and a click event will be added to the switch control.
Add a click event, that is, the switch is closed

 lv_obj_add_state(guider_ui.screen_sw_1,LV_STATE_CHECKED);
清除点击事件,也就是开关打开
lv_obj_clear_state(guider_ui.screen_sw_1,LV_STATE_CHECKED);

#3. Part of the code

    pinMode(LED,OUTPUT);
    pinMode(key, INPUT);
}
    bool state_led = 0;
    uint8_t key_state = 0;
void key_scan()
{
    
    
    if(digitalRead(key)==LOW){
    
    
        delay(10);
        if(digitalRead(key)==LOW){
    
    
            key_state++;
            if(key_state>=200) key_state =200;
        }
    }
    else key_state = 0;
}
void loop()
{
    
        key_scan();
    if(key_state==2){
    
    
        state_led = !state_led;
        if(state_led){
    
    
        digitalWrite(LED,LOW);
        lv_obj_clear_state(guider_ui.screen_sw_1,LV_STATE_CHECKED);
        }


        else {
    
    digitalWrite(LED,HIGH);
           lv_obj_add_state(guider_ui.screen_sw_1,LV_STATE_CHECKED);
        }
    }
    lv_timer_handler(); /* let the GUI do its work */
    delay( 5 );
}

ps: I do not recommend the above method, because it consumes resources very often, causing LVGL to run very slow. LVGL has built-in keyboard, mouse, and encoder interfaces, so it is most suitable to use the above devices when there is no touch screen.

おすすめ

転載: blog.csdn.net/amimax/article/details/127351352