How to update a label object to show sensor value

Description

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

ESP32

What LVGL version are you using?

V8.1

What do you want to achieve?

Lebel gets update to show sensor values

What have you tried so far?

Almost all methods by using Platform IO in VS code.

Code to reproduce

Add a code snippet which can run in the simulator. It should contain only the relevant code that compiles without errors when separated from your main code base.

The code block(s) should be formatted like:

#include <lvgl.h>
#include "lv_conf.h"
void Show_Info();
void lv_buttons();

void setup(){
      lv_buttons();
}
void loop()
{
      lv_timer_handler(); /* let the GUI do its work */
      show_info();
}

void Show_Info(){
      String P_Str = String(analogRead(A0));
      lv_obj_t *label_Pre = lv_label_create(lv_scr_act());
      lv_label_set_text(label_Pre, P_Str.c_str());  // set label text
      lv_obj_set_style_text_font(label_Pre, &lv_font_montserrat_48, 0);
      lv_obj_align(label_Pre, LV_ALIGN_TOP_LEFT, 20, 10); 
}

void lv_buttons(){
...
}

After uploading, it runs well kept updating for 10 seconds and stuck. I believe the loop is keep creating object label_Pre until memory runs out.

Therefore, I move the lv_obj_t *label_Pre = lv_label_create(lv_scr_act()); outside of the function and placed it in setup() to run only once when powering on.

However, the lv_label_set_text(label_Pre, P_Str.c_str()); complained “identifier “label_Pre” is undefinedC/C++(20)”.

I tried many times but could not make it work. Pls help!

Also, I tried lv_task but does not supported in V8.
I tried LV_EVENT_REFRESH, no hope.

static void Sensor_valve_handler(lv_obj_t * obj, lv_event_t event){
if (event == LV_EVENT_REFRESH ) 
    {
        lv_label_set_text(label_Pre, P_Str.c_str());  // set label text
    }
}

Same issue, the lv_label_set_text(label_Pre, P_Str.c_str()); complained “identifier “label_Pre” is undefinedC/C++(20)”.

Set lv_obj_t * label_Pre as a global object.
Then in your setup code call
label_Pre = lv_label_create(lv_scr_act());

And in your loop function call lv_label_set_text(…)

This will fix your initial issue of the memory leak causing your device to get stuck, and allow you to update it from your loop.

Very nice! It worked for me.
Thanks a lot, David!

1 Like

My pleasure!