[Solved] Time.now() returning unexpected value

Hi everyone!

I am having trouble with some unpredictable Time.now() behaviour even after reading numerous other threads.

I cannot for anything in the world make it return a unix timestamp to a Particle.variable, either using sprintf or the String class. In the docs it is described that Time.now() should return an integer, which both methods should be capable of converting.

I have tried numerous methods already and it would be inefficient for me to post all of them. I am providing a minimum example using sprintf that at least returns something. String() returns nothing at all in the Particle.variable.

void setup() {
char theTime[100];
sprintf(theTime, "%i", Time.now());
Particle.variable("data",theTime);
}

void loop() {
}

The resulting Particle.variable reads:

{
  "cmd": "VarReturn",
  "name": "data",
  "result": "�T",
  "coreInfo": {
    "last_app": "",
    "last_heard": "2016-09-29T11:31:55.395Z",
    "connected": true,
    "last_handshake_at": "2016-09-29T11:31:49.423Z",
    "deviceID": "2d0030001747353236343033",
    "product_id": 6
  }
}

In another thread it was mentioned that %i should rather be %u in sprintf, but I find the results are exactly the same.

Any good suggestions to why my time is “�T”? Thanks in advance!

The problem is that Particle.variable() takes a reference to a variable and keeps it until the cloud requests the value of the variable. Typically, the variable passed as the second parameter must be a global variable for this to work properly.

If you move the declaration of char theTime[100] to be outside of setup, it should work. The reason for the garbage characters is that you’ve declared theTime on the stack, and once setup exits, there will be something else on the stack instead of the value you have written there.

3 Likes

And so it does! Thank you for the explanation of how the Particle.variable works, I did not know that beforehand. It will definitely save me some trouble in the future.

1 Like

Thanks @rickkas7 for the help!