Can't use srand(time(NULL)) with Particle

I’m trying to initialise my random numbers using srand(time(NULL)); like everyone recommends online. I’m including <time.h> at the top of my file.

When I try to compile on Particle Dev it gives me this cyptic error:

An when I click it to check what’s wrong with it I see this conflicting “informational” message:

This is really getting on my nerves.
What’s wrong? Is this a bug or am I doing something wrong?
Is there any alternative to using time(NULL)? I tried millis() and it worked without any includes, is it equivalent?

The time(NULL) function relies on gettimeofday(), which is not implemented on the Particle platform, which results the not very helpful build did not produce binary error.

As long as you are connecting to the cloud, it’s not necessary to seed the random number generator because it will be seeded by a true random number from the cloud.

millis() is a poor choice because it starts at 0 every time you boot. If you are running without the cloud I’d seed it with HAL_RNG_GetRandomNumber(), a true 32-bit random number generated by the STMF32 processor. You don’t need to include anything to use the function.

1 Like

Your reply was really really helpful!

So for people who are not connected to Particle’s cloud, they should use:

random(10); //random numbers between 0 and 9

If they are connected to the cloud (which is my case), they should use instead:

random(10); //random numbers between 0 and 9

Because the could already seeds the random appropriately?

Yes, though the Arduino-style randomSeed() and random() calls are just wrappers for the Unix-style srand() and rand() calls, so you can use either. Both will be seeded and function properly.