1
float random_value(int min, int max)
{
        float temp = rand() / (float) RAND_MAX;
        return min + temp *(max - min);
}

I have this function, but it is not working in cooja, as it always output the same numbers over and over again, and I don't have the time.h library to make srand(). So, how should I print different random float values in cooja? I should write a c function float random_value (float min, float max) that could be used to implement virtual temperature sensor that could be configured to generate values between min and max value.

Andy J
  • 1,479
  • 6
  • 23
  • 40
user2
  • 13
  • 1
  • 5
  • Have a read of this: https://stackoverflow.com/questions/61012155/how-to-have-a-random-number-which-changes-with-time-in-cooja-simulator-in-c-lang it looks like it is exactly what you are asking. And this: https://www.javaer101.com/en/article/39171545.html – Jerry Jeremiah May 04 '21 at 22:51

2 Answers2

2

If you don't have access to time.h to seed the pseudo-random number generator, another way to use the current pid of the currently-running process.

In fact, unique filenames are sometimes generated this way:

getpid() returns the process ID (PID) of the calling process.
(This is often used by routines that generate unique temporary
filenames.)

Here's a small example that prints the current pid and uses it as an argument to srand():

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
int main() {
   int pid;
   pid = getpid();
   printf("Current process pid = %d\n", pid);
   srand((unsigned int)pid);
   printf("Random number: %d\n", rand()%100);
   return 0;
}

Running it once:

Current process pid = 197
Random number: 8

Running it again:

Current process pid = 5612
Random number: 76 
Andy J
  • 1,479
  • 6
  • 23
  • 40
0

If you run on Linux, read random(7). you could seed your PRNG by using the getrandom(2) system call or by opening the /dev/random device (see random(4))

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547