Random Number Generation using C

Discussion in 'Programmer's Corner' started by San_Dendlek, Mar 24, 2010.

  1. San_Dendlek

    Thread Starter New Member

    Mar 24, 2010
    11
    0
    Hi, I want to generate a random numbers for my PIC 16F84A.
    I am using MPLAB to write the program.

    My project is basically that I have 8 leds connected to PORTB of the PIC and I want to generate countinously random numbers between 1 and 255.

    Any help is appreciated thanks in advance.
     
  2. AlexR

    Well-Known Member

    Jan 16, 2008
    735
    54
    Most C compilers have a library function rand() that generates a pseudo-random number. Read your C manual to see the details of how to use it.
     
  3. braeden

    Member

    Feb 6, 2008
    17
    0
    Note sure if this helps but i wrote a c++ program awhile back to generate random numbers. I know your looking for C but perhaps you can make it work.

    here you go:

    Code ( (Unknown Language)):
    1. // C++ Random Number Generator
    2.  
    3.  
    4. #include <windows.h>
    5. #include <iostream>
    6. using namespace std;
    7.  
    8. int main()
    9. {
    10.     srand(GetTickCount());
    11.     int i = rand()%250; //%250 sets the max number.
    12.     cout << i;
    13.     cin.get();
    14.     return 0;
    15. }
    16.  
    17.  
    18.  
    19.  
     
  4. someonesdad

    Senior Member

    Jul 7, 2009
    1,585
    141
    The easiest is to use your library's random number generator. There's a huge amount of literature on random number generation. To do your due diligence, consult Knuth's The Art of Computer Programming. The Numerical Recipes in C book contains some cookbook routines for random number generation. I suggest doing a bit of reading on the subject, as a naive user can be dangerous if he/she thinks it's easy to make up their own random number generator. :p
     
  5. t06afre

    AAC Fanatic!

    May 11, 2009
    5,939
    1,222
  6. San_Dendlek

    Thread Starter New Member

    Mar 24, 2010
    11
    0
    Thanks to all of you let me try your solution i will let you know
     
  7. San_Dendlek

    Thread Starter New Member

    Mar 24, 2010
    11
    0
    Thanks to all of you I found out how to make this. Especially thanks to AlexR and braeden you gave me the idea. I have a beginner backgound in C and C++ i was using the rand() function wrongly.
     
Loading...