Concatenated String Doesn't Send Correctly



  • Hi all!

    I'm working with sending messages from one of my sensors back to my controller for the first time, and I'm a little stumped...

    I have this message defined:

    MyMessage msg(CHILD_ID_LIGHT, V_VAR1);
    

    And this code that uses it to send a message to the controller

    void open_scratchpad(int expectedScratchpadValues) {
      send(msg.set("Scratchpad is open"));
      send(msg.set("string " + String(expectedScratchpadValues)));
    }
    

    I expect to get the following messages back (in this example, expectedScratchpadValues=4):

    2;1;1;0;24;Scratchpad is open
    2;1;1;0;24;string 4
    

    Instead, I get:

    2;1;1;0;24;Scratchpad is open
    2;1;1;0;24;0
    

    But if I do

    Serial.println("string " + String(expectedScratchpadValues)
    

    then the arduino console correctly prints

    string 4
    

    Never mind the exact code here. I'm just playing around to learn the messaging protocol, so it really doesn't mean much of anything. I just want to be able to convert ints to strings, concatenate those strings, and then pass that concatenated result back to my controller.

    Thanks for you help!



  • @mrmuszynski
    Hi, there are some setters for message payload types but none for type String, see: Message manipulation.

    You need to convert the resulting String into const char* like this:

    send(msg.set(("string " + String(expectedScratchpadValues)).c_str()));
    

    But in general I would try to avoid usage of the String data type, especially for the use case in your code example. You could use e.g.:

      char str[80];
      sprintf(str, "string %d", expectedScratchpadValues);
      send(msg.set(str));
    

    For Arduino String read more e.g. here: The Evils of Arduino Strings

    HTH


Log in to reply
 

Suggested Topics

0
Online

11.2k
Users

11.1k
Topics

112.5k
Posts