Button Color Change Error -- Guru Meditation Error: Core 1 panic'ed

Description

i want to change button color when i clicked button but not working

What MCU/Processor/Board and compiler are you using?

2.8inch_ESP32-2432S028R

What LVGL version are you using?

8.3.9

What do you want to achieve?

What have you tried so far?

Code to reproduce

static void btn_event_cb2(lv_event_t* e) {
  lv_event_code_t code = lv_event_get_code(e);

  if (code == LV_EVENT_CLICKED) {
    client.subscribe(mqtt_topics[0]);
    client.setCallback(callback);
    if (buttonState) {
      lv_style_init(&style_btn_red);
      lv_style_set_bg_color(&style_btn_red, lv_color_make(0, 255, 0)); // BLUE RED GREEN 
      lv_style_set_bg_opa(&style_btn_red, LV_OPA_COVER);
      lv_obj_add_style(btn, &style_btn_red, 0);
      client.publish(mqtt_topics[0], "0");
    } else {
      lv_style_init(&style_btn_red);
      lv_style_set_bg_color(&style_btn_red, lv_color_make(0, 0, 255)); // BLUE RED GREEN 
      lv_style_set_bg_opa(&style_btn_red, LV_OPA_COVER);
      lv_obj_add_style(btn, &style_btn_red, 0);     
      client.publish(mqtt_topics[0], "1");
    }
  }
}

Screenshot and/or video

Styles should get initiated globally, not during the function running.

Try


lv_style_t style_btn_red;
lv_style_t style_btn_blue;

static void init_styles() { //somewhere in your init code run init_styles()
  lv_style_init(&style_btn_red);
  lv_style_set_bg_color(&style_btn_red, lv_color_make(255, 0, 0)); // RGB
  lv_style_set_bg_opa(&style_btn_red, LV_OPA_COVER);
  
  lv_style_init(&style_btn_blue);
  lv_style_set_bg_color(&style_btn_blue, lv_color_make(0, 0, 255)); // RGB
  lv_style_set_bg_opa(&style_btn_blue, LV_OPA_COVER);
}


static void btn_event_cb2(lv_event_t* e) {
  lv_event_code_t code = lv_event_get_code(e);

  if (code == LV_EVENT_CLICKED) {
    client.subscribe(mqtt_topics[0]);
    client.setCallback(callback);

    if (buttonState) {
      lv_obj_add_style(btn, &style_btn_red, 0);
      client.publish(mqtt_topics[0], "0");
    } else {
      lv_obj_add_style(btn, &style_btn_green, 0);     
      client.publish(mqtt_topics[0], "1");
    }
  }
}

Also, you need to look at what buttonState is.