I know there are similar posts to this. I have tried all of them. But that doesn't answer my question. I have already tried srand which is provided by c, but it doesn't work in cooja.
I have also tried #include "cfs/cfs.h"
, #include "cfs/cfs-coffee.h"
. But that provide static random number.

- 156
- 4
- 15
-
2How does srand and rand not work in cooja? – Aplet123 Apr 03 '20 at 12:44
-
@Aplet123 rand is working but there is no #include
in cooja. I wanted to use this library because it uses the current time as a seed for a random generator as follows: srand(time(0)); – Akash Patel Apr 04 '20 at 14:13
1 Answers
Use node_id
to initialize the random number generator.
In Contiki, you should use random_init()
and random_rand()
instead of the C library functions:
#include <sys/node-id.h>
/* ... */
random_init(node_id);
unsigned short r = random_rand();
Edit: this will give you different random numbers on different nodes. If you want different random numbers in different simulations runs, you can use the Cooja mote platform. It initializes the Contiki RNG from the simRandomSeed
variable, which is the simulation's random seed that you can set to a different value each time (from command line or in the .csc file).
If you're not using Cooja motes and do not want to assign different node IDs in different simulations runs, the only option is to get the random seed on the mote via an external interface, e.g. send it over the serial port and read it on the node.

- 8,136
- 3
- 28
- 52
-
But node id is static, so it will create the same set of random numbers every time. I want a different set of random number each time. – Akash Patel Apr 09 '20 at 15:36
-
If you can tell something that is random every time. So I can put that in random_init. – Akash Patel Apr 09 '20 at 15:53
-
Which header file contains the simRandomSeed? As I am getting error: ‘simRandomSeed’ undeclared (first use in this function) – Akash Patel Apr 12 '20 at 08:27
-
1You can declare it yourself as `extern int simRandomSeed`, there is no header file unfortunately. – kfx Apr 13 '20 at 10:02
-
https://stackoverflow.com/questions/61010848/how-can-i-have-a-128-bit-integer-in-protothread-in-cooja-simulator Can you please look at these question too. – Akash Patel Apr 14 '20 at 11:48