}

1/08/2012

Random flasher - Arduino project demonstrating random number generation

Arduino random flasher


Very simple circuit and program.  The entire 'project' took about 15 minutes to build/code once I read up on Arduino random numbers.  This Arduino program simply selects a random pin and sets it high for a random amount of time - over and over again.

The Arduino command random is very easy to use vs. the 'c' counterpart.

random (x,y) will generate a random number between x and y, including x but not y.  So if you want a number between 1 and 11 you would use ranNumb = random(1,12);  - assuming ranNumb is of integer type.

randomSeed(analogRead(0)); reads a random signal from the ADC on Analog port 0 - much better than seeding your RNG off of the clock like your PC would have to do.  Here's the code.


// Random flasher by Lonnie Honeycutt
// Simple circuit and program to demonstrate random number
// generation and integration into your circuit on the
// arduino.
//
// Circuit build : Simply connect 3 LED's to pins 8,9,10
// Be sure to connect a resistor to each LED.  I used 330 ohms.
//
//
int ranNum;
int ranDel;
void setup() {
// Seed RNG from analog port.
randomSeed(analogRead(0));
// Setup 3 output ports for LED's
pinMode(8, OUTPUT);
pinMode(9, OUTPUT);
pinMode(10, OUTPUT);
}
void loop() {
    //Generate random number between 8 and 10
    ranNum=random(8,11);
    // Generate random delay time
    ranDel=random(25,300);
    //Turn on the LED
    digitalWrite(ranNum, HIGH);
    delay(ranDel);
    //Turn off the LED
    digitalWrite(ranNum, LOW);  
}