String as global variable

I’m trying to define a global var that can store a string. First problem is the right way to define the string (char[] or String?), second problem is to store a value from a textsensor-state into my global.
Here is an example for both of my problems:

globals:
  - id: testglobal
    type: char[5]
    restore_value: no
    #initial_value: '{"a","b","c","d"}'  # does not compile
    #initial_value: '"abcd"'             # does not compile


text_sensor:
  - platform: version
    name: textsensor1
    id: text1
    on_value:
      then:
        - lambda: |-
            ESP_LOGD("main", "text1 = %s", id(text1).state.c_str());
            ESP_LOGD("main", "testglobal = %s", id(testglobal));
            ESP_LOGD("main", "copy testglobal to text1.state:");
            id(text1).state = id(testglobal);
            ESP_LOGD("main", "text1 = %s", id(text1).state.c_str());
            ESP_LOGD("main", "testglobal = %s", id(testglobal));

binary_sensor:
  - platform: gpio
    pin: 
      number: D4
      mode: INPUT_PULLUP
    name: "testing switch"
    filters:
      - delayed_on: 20ms
    on_state:
      then:
        - lambda: |-
            ESP_LOGD("main", "copy text1.state to testglobal:" );
            id(testglobal) = id(text1).state;


If I compile the code above, I get an error (with initial value even more):

src/main.cpp: In lambda function:
src/main.cpp:178:27: error: incompatible types in assignment of 'std::string {aka std::basic_string<char>}' to 'char [5]'
       testglobal->value() = text1->state;
                           ^
*** [.pioenvs/pctext/src/main.cpp.o] Error 1

I’m new to C++, so maybe anyone can point my in right direction?

Thanks in advance
tomesp

1 Like

try this:

type: char[5]
initial_value: β€œ{β€˜a’,β€˜b’,β€˜c’,β€˜d’}”

FYI For those of you that the above suggestion does not work for, the character set used (single quote type) was the problem for me.
The SINGLE QUOTATIONS were not understood at validation / compile time by my system, so I had to change them to my own (from my own keyboard, windows running python / esphome), and then it worked:

initial_value: "{'b','o','o','t'}"     # MY FIX
#  LOOK CLOSELY at the single quotes, different from these: β€œ{β€˜a’,β€˜b’,β€˜c’,β€˜d’}”

shahidsiddiquimax x

Apr '20

try this:

type: char[5]
initial_value: β€œ{β€˜a’,β€˜b’,β€˜c’,β€˜d’}”

For future answers, the correct way of declare global string:

  • id: id_user
    type: std::string
    restore_value: no
    initial_value: β€˜β€œhello world”’
6 Likes