I have to generate a random number by taking the input as a timer value... SO can anyone suggest how to get this????
Thanks in Advance
Did you spend some time with Google?
Did you get any ideas from all the links Google can supply?
Where did you get stuck? What do you want clarified?
yes, All are using the random function to generate random number... In embedded C can we use this rand function???
No normal implementation of rand() will generate any random number.
rand() generates a pseudo-random number.
Good enough for some tasks, but much too lousy for lots of problems.
But besides rand() you also needs to start this virtual number sequence with a seed. This can be done with srand(). But what randomness do you have access to in your product, that will make sure that if you power up your unit 100 times, you get 100 different seed values?
Equipment connected to a serial terminal may use the pause between received characters to seed the rand() generator. Same if device have ethernet.
But in the end, _you_ must figure out how you can get your device to produce different sequences every time you start it. And it isn't trivial.
A hint ... don't bother with the one I saw during a code review recently:
. . srand(rand()); . .
srand(rand());
That was a real beauty.
With such code, the guilty part should buy a nice cake or something.
Sorry for my very limited English and technical ability, I guess this
is a really bad idea, am I right?
The srand() function uses the argument as a seed for a new sequence of pseudo-random numbers to be returned by subsequent calls to rand(). If srand() is then called with the same seed value, the sequence of pseudo-random numbers shall be repeated. If rand() is called before any calls to srand() are made, the same sequence shall be generated as when srand() is first called with a seed value of 1.
I noticed that it is 1-Apr-2011 now. But just not so sure.
"...a really bad idea, am I right?"
Yes, you are right.
No, it is nothing to do with April 1st. I really did see that line of code!
The line of code was being executed close to the start of main, so the seed for the pseudo-random number generator had been set by the initialisation of the library. The first random number produced was identical from one reset to another. So the value passed to srand was always the same. So subsequent calls to rand always produced the same sequence of values.