Society of Robots - Robot Forum
Software => Software => Topic started by: Tomomastchi-project on December 01, 2008, 11:50:08 AM
-
Hi,
While I was testing the algorithm I desiged, I had a problem with the PRNG I wanted to use. Because I often use random numbers in my program, I made a function. It goes like this:
int gen_rand(void) /* gives a random value between 1 en 100 */
{
srand(time(NULL)); // random seed, depending on clock
return(rand() % 100 + 1);
}
Every time I use gen_rand(), it returns the same value. I included stdio.h and stdlib.h. Even when I try to use time.h it results in the same problem. What am I doing wrong? (using GNU GCC compiler)
I also have another question: Where can I find good code in C de reverse engineer? I am going to use the C18 compiler with a PIC 18F4550.
Thanks
-
Here's the function I use. It need some kind of initiating function - I use an internal clock function called readRTC(), but you probably have a clock function you can access ...
/* infamous 0xDEADBEEF pseudo-random number generator by
Robbert Haarman http://inglorion.net
returns number between 0x0000 and 0xFFFF */
int rand() {
static int deadbeef_seed, deadbeef_beef;
if (deadbeef_beef == 0xdeadbeef) // initialize
deadbeef_seed = readRTC();
deadbeef_seed = (deadbeef_seed << 7) ^ ((deadbeef_seed >> 25) + deadbeef_beef);
deadbeef_beef = (deadbeef_beef << 7) ^ ((deadbeef_beef >> 25) + 0xdeadbeef);
return (deadbeef_seed & 0x0000FFFF); // return rand number from 0x0000 to 0xFFFF
}
-
Thanks, now I have my program finally working. Though I still wonder why the old thing didnt work.
But does anyone know the answer to my other question?
-
Thanks, now I have my program finally working. Though I still wonder why the old thing didnt work.
But does anyone know the answer to my other question?
You should only call 'srand' once - somewhere in your initialisation code. You are calling it every time you generate a new random number. The time() function probably also relies on an internal system clock - which mcus dont have. So srand is probably always setting the seed to the same value initial value. And since you do this every time before you call rand() then rand will always return the same number.
-
As webbot was saying, computers are incapable of producing truly random numbers - they all read from a preprogrammed list of 'random' numbers.
The most popular solution is to use a timer or special external hardware.
This will work on my Axon with two lines of code, but isn't as 'random' as other methods:
srandom(TCNT0);
random_number=rand();
The timer method however fails when a human isn't in the loop (push enter to start, etc.).