crandomcontikicooja

How to have a random number which changes with time in cooja simulator in c language?


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.


Solution

  • 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.