how to send a random number

Go To Last Post
4 posts / 0 new
Author
Message
#1
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Hi Freaks......
I need to select a random number between 0 to 5 .
The number should be choosen and load into a variable called select_number which is an integer.

I was looking in the CodeVision Manual to see how to call this random function but i saw that it returnes a number of 32767.

I dont really understand that .....
Please advise..

Thanks

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

If you could manage a range of 0-7, then you could take that int value and mask out all but the low 3 bits. That is, do a bitwise-AND with 0x07.

You would not be able to do the same with 5 because that would throw away the random values of 0x02 and 0x03.

Jim

 

Until Black Lives Matter, we do not have "All Lives Matter"!

 

 

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

tzif wrote:
I was looking in the CodeVision Manual to see how to call this random function but i saw that it returnes a number of 32767.

I think you meant that random( ) returns a maximum value of 32767. Assuming that you want an integer between 0 and 5 inclusive, take the result returned by random( ) modulo 6. That is:

select_number = random( ) % 6;

Don

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Hi!
Soonly I've needed to generate a random number from 0 to 7. It's not easy to generate It programly. You can generate a pseudo-random number with your software, but It's predictable even your algorithm is based on DES (that is one of the best algorithms for pseudo-random number with long period, and It's difficult to predict, and It's used in military radios with frequency hopping). So, the easyest way is to use a random noise source. Basicly this is implemented with zener diode. Then the signal is amplified and the resulting noise pulses are send to comparator. So, set your timer/counter in your AVR to be clocked by external pulses (from the comparator), and compare registers to your desired MAX number minus 1. And also set clear timer on compare match. And when you want to generate a trully random number just read your Timer/Counter.
Regards!