String Class and Spark Variable

I’m new to C and am missing something here. How can I use String class with Spark variable?

String OutStr;

void setup() {
Spark.variable(“String1”, OutStr, STRING);
OutStr = “”;

Thank you in advance.

Steve

The Spark.variable() kind of string is the C/C++ char array string, not the Arduino String class, but it is easy to convert:

String OutStr;
char varStr[65];

void setup() {
  Spark.variable("String1",varStr, STRING);
}

void loop() {
...
  //update string variable
  OutStr.toCharArray(varStr,65); //max length
...
}
1 Like

Thank you bko!!!
If OutStr is not a char array string what is it?

Hi @Tucker

The String class is an Arduino Wiring object doc’ed here

http://docs.spark.io/firmware/#language-syntax-string-class

and here

http://arduino.cc/en/Reference/StringObject

@christine @bryce

This particle.variable() always seems to give me problems. Presently I need to figure out how to send a group of variables to a webpage for further processing, seems like packaging the variables as a fake jSON object may be a good solution, but before I get to that, the Particle Firmware Reference has a strange line at

https://docs.particle.io/reference/firmware/photon/#particle-variable-

The line is

  if (Particle.variable("mess", message)==false)
      // variable not registered!
 Particle.variable("mess2", aString);

The syntax here confuses me, could someone please put in some curly brackets as needed or just change the code to something like

  if (Particle.variable("mess", message)==false){
      // variable not registered!
 }
 Particle.variable("mess2", aString);

since the present Firmware example seems to never let “aString” work, unless you somehow make the first “message” char array pointer become not registered! :fearful:

Anyway if I ignore the example code, my working code looks like:

String theString;
int x1,y1,x2,y2,x3,y3;

void setup()
{
   void random_seed_from_cloud(unsigned int seed);

    Particle.variable("myString", theString);
}

void loop()
{
    x1 = random(1, 99);
    y1 = random(1, 99);
    x2 = random(1, 99);
    y2 = random(1, 99);
    x3 = random(1, 99);
    y3 = random(1, 99);

   theString = String( "x1=" + String(x1) + ", y1=" + String(y1) + ", x2=" + String(x2) + ", y2="+String(y2) + ", x3=" + String(x3) + ", y3=" + String(y3) );
   
}

So if I throw something like this into my browser

https://api.particle.io/v1/devices/00000000000/myString?access_token=aaaaaaaaaaaaaaa

where the 000000000 are my ID and the aaaaaaaaaaaa are my access token then I get a result like

{
  "cmd": "VarReturn",
  "name": "myString",
  "result": "x1=17, y1=30, x2=21, y2=23, x3=47, y3=37",
  "coreInfo": {
    "last_app": "",
    "last_heard": "2015-11-05T06:37:15.434Z",
    "connected": true,
    "last_handshake_at": "2015-11-05T06:34:52.260Z",
    "deviceID": "00000000000",
    "product_id": 6
  }
}

Which looks reasonably useful. Now, I just have to remember how to use AJAX to load this back into javascript and I think I am set.

1 Like

True, the doc sample code is rather misleading, but you could just edit that - it’s open source and open for update right in there.

But for your string building, have you considered sprintf() or the new String::format() function?
I think this would make your code and intended output format much more readable (and reduce heap usage too).


Edit: I’ve “corrected” the confusing syntax there

1 Like

Nope. Haven’t used either of those functions, but I did get my Ajax page working.


<html>
<body>

<button type="button" onclick="{loadDoc()}">Change Content</button><br><br>

x1= <input id="myx1" type=text placeholder="variable x1 returned from Particle.io" size=50><br>

<div id="demo"><h2>Let AJAX change this text</h2></div>

<script>
function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
      myResult = JSON.parse(xhttp.responseText).result;

      document.getElementById("demo").innerHTML = myResult;

      myResultArray = myResult.split(",");
      myx1Array = myResultArray[0].split("=");
      document.all.myx1.value = parseInt(myx1Array[1]);  
     
    }
  }
  xhttp.open("GET", "https://api.particle.io/v1/devices/0000000000000/myString?access_token=aaaaaaaaaaaaa", true);
  xhttp.send();
}
</script>

</body>
</html>

The output looks like:

I just saw a problem with my own code. Thanks @ScruffR, using your ideas I think I can improve this to make the output real JSON that I can properly parse using javascript JSON.parse(). Will try to fix it today.

1 Like

@ScruffR @christine

So I changed the code and things are much better, except for two irritating issues with String:format. How do I insert a new line and how to get rid of the slashes?

In javascript I can use a single quote to surround double quotes when needed. example: var x = 'Joe said “Hello” ’ . With String:format that does not work. Also if I want to print a new line I send /n or is it (\n), but that does not work. The output is very messy but actually does the correct job, since javascript JSON.parse() is smart enough to figure things out. He is my code:

the .ino

String theString;
int x1var, y1var, x2var, y2var, x3var, y3var;


void setup()
{
    void random_seed_from_cloud(unsigned int seed);
    Particle.variable("myString", theString);
}

void loop()
{
    x1var = random(1, 99);
    y1var = random(1, 99);
    x2var = random(1, 99);
    y2var = random(1, 99);
    x3var = random(1, 99);
    y3var = random(1, 99);

    theString = String::format("{\"x1\": \"%d\", \"y1\": \"%d\", \"x2\": \"%d\", \"y2\": \"%d\", \"x3\": \"%d\", \"y3\": \"%d\"}", x1var ,y1var ,x2var ,y2var ,x3var ,y3var );
     
}

And the AJAX webpage is:

<html>
<body>

<button type="button" onclick="{loadDoc()}">Change Content</button><br><br>

x1= <input id="myx1" type=text placeholder="variable x1 returned from Particle.io" size=50><br>

<div id="demo"><h2>Let AJAX change this text</h2></div>
<textarea id="demo2" rows=20 cols=70>Let AJAX change this text</textarea>


<script>
function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
      myResult = JSON.parse(xhttp.responseText).result;    // only grab the result

      document.getElementById("demo").innerHTML = myResult;
      document.getElementById("demo2").value = xhttp.responseText;

      myParticle = JSON.parse(myResult); 

      document.all.myx1.value = myParticle.x1     // grab x1 from myResult
     
    }
  }
  xhttp.open("GET", "https://api.particle.io/v1/devices/00000000/myString?access_token=aaaaaaaaaaaaa", true);
  xhttp.send();
}
</script>

</body>
</html>

As before use 0000000 as your device ID and aaaaaaaa as your access token.

Here is an image of the output and you can see it is really messy. Not very nice JSON formatting, but it does work and I can extract the individual information

Any suggestions to tidy this up a bit.

A new line will be added via "\n" but it will also be displayed as such, since you are not actually printing the string, but looking at its representation in “C form” (or any language adopting the C encoding scheme). If you printed this string to the console you should not see the escaped form but the actual result of the byte, causing a new line (but often not causing a carriage return - which would be “\r”)
And I think the same goes for the slashes in “\"”, they are actually not really there, they’re just the common escape character to distinguish the syntactic double-quote wrapping a string from the double-quote as part of the string.
To test my “theory” try to Serial.print(theString); and see what a serial monitor gives you (including a \n).

But I have to admit I’m no pro when it comes to JS or AJAX :blush:
Just a thought which might not work, but maybe worth a try. If you replace the escaped double-quote (\") with a single-quote (') will JSON.parse() still understand your string?
At least in JS both versions seem to be interchangable (in some cases).


As a illustration what I mean with the escaping of special characters, you could take the HEX notation 0x10 the 0x only denotes a representation scheme (distinguishing it from DEC 10 or 0b10) but is not actually part of the number (DEC 16 or BIN 10000).

I think JSON.parse() is fairly strict about the double quotes not single quotes, but I can test it.

What is really good, is the output from the particle.function() or particle.variable(). They format JSON really well with nice carriage returns. Can anyone point me to the location of particle.function() or particle.variable() on the github site so I can look at how particle does it?

If I search for function or variable I get hundreds of hits.

That formatting happens in the cloud, not the firmware. For firmware using \" is really the best way.

1 Like

As @bko said, but just for completeness you’ll find the implementations in spark_utilities.cpp.

1 Like

@bko, forgot about the cloud. Good point, I think I will just format the string from javascript. The big deal is that it works great. Thanks for the help.

@ScruffR Thanks. The url is

here

@christine

This is only connected to Particle.io since I made the AJAX page to help with the Photon.

I just took the AJAX page, created here, to help extract JSON data from the WIFI capable IP Camera. It allows webpage access to every sensor on your Android cell phone! Ridiculous amount of information being streamed every 80 milliseconds.

See Github at https://github.com/hpssjellis/ip-camera-json-ajax-on-a-webpage

It has images, if you have never used the IP camera. (Kind of like a one way version of Skype.)