-2

I am trying to send my sensor data through gprs using esp32 and ai thinker a9 gsm module. I want a variable of type int/float (int) to be added between the string as follows:

post = ""{"nodeId": "32456781xxxxxxx", "value": {"temperature": int }}"";

problem i am facing is i am unable to add my post variable in double quotes as per requirement of AT commands.

For more info refer my output image and the problem i am facing which i need to be solved

enter image description here

enter image description here

i want that marked text between double quotes as shown in image 2.

Thanks

2 Answers2

1

C++ and "Arduino" (to the extent that it can really be called a "language") don't do string interpolation. You basically have to cobble the string together yourself using snprintf or std::ostringstream (which you'd have on the ESP32). The Arduino String class also supports concatenation of non-string things onto the end of it.

Between the those options snprintf can probably be used more efficiently, something like this:

int some_int_variable = 7; // for example
char post[REASONABLE_UPPER_BOUND]; 
snprintf(
    post, sizeof post, 
    R"xyzzy({"nodeId": "32456781xxxxxxx", "value": {"temperature": %d }})xyzzy",
    some_int_variable
);

// do something with resulting post variable.

If you're wondering what the R"xyzzy(, and )xyzzy", it's a raw string literal, an alternative to escaping the double quotes.

That said, since you're working with JSON, it may make a lot more sense to use ArduinoJSON to construct your JSON object in an ArduinoJSON document as you can see in this example. They're serializing it to a stream; if you're using StaticJsonDocument, this may not require any dynamic (re)allocation(s). If you actually need it to result in a String (and you may not actually) you can see how that is done here.

timemage
  • 536
  • 1
  • 4
  • 12
0

Add a backslash before inerr double quotes, something like this:

"\"{\"nodeId\": \"32456781xxxxxxx\", \"value\": {\"temperature\": int }}\""
Nino
  • 702
  • 2
  • 6
  • 12