How to use random();?

Post here about your Arduino projects, get help - for Adafruit customers!

Moderators: adafruit_support_bill, adafruit

Please be positive and constructive with your questions and comments.
Locked
User avatar
phnxfirestorm
 
Posts: 30
Joined: Wed Jan 18, 2012 10:28 pm

How to use random();?

Post by phnxfirestorm »

So I have heard there is a random method you can use to make your code on the Arduino breakout board atmega32u, and the LED strip, to show up at random instead of the coded sequence. My issue is I don't know how to implement the code. I don't like the code going in order. It doesn't look as interesting.

If you need it I'll edit this post and add my code.

User avatar
adafruit_support_bill
 
Posts: 88091
Joined: Sat Feb 07, 2009 10:11 am

Re: How to use random();?

Post by adafruit_support_bill »

http://arduino.cc/en/Reference/Random
Here's some code I use for a Halloween display:

Code: Select all

#include "WS2801.h"

/*****************************************************************************
Random Eyes sketch for WS2801 pixels
W. Earl 10/16/11

Randomized pairs of led pixels look like eyes peering from the darkness.

Blinking is implemented as an array of state machines so that multiple pairs
of eyes can be active concurrently, but in different phases of a blink.
*****************************************************************************/

int dataPin = 4;      
int clockPin = 3;  

const int numPixels = 25;  // Change this if using more than one strand

const int maxEyes = 3; // maximum number of concurrently active blinkers

/*****************************************************************************
Note - this code was developed on an Atmega-168.
You may need to adjust timings somewhat for a faster processor.
*****************************************************************************/
// dead-time between lighting of a range of pixels
const int deadTimeMin = 50;
const int deadTimeMax = 500;

// interval between blink starts - independent of position
const int intervalMin = 10;
const int intervalMax = 300;

WS2801 strip = WS2801(numPixels, dataPin, clockPin);

/*****************************************************************************
Blinker Class

Implements a state machine which generates a blink of random duration and color.
The blink uses two adjacent pixels and ramps the intensity up, then down, with 
a random repeat now and again.
*****************************************************************************/

class blinker
{
  public:
  
  boolean m_active;  // blinker is in use.
  int m_deadTime;  // don't re-use this pair immediately
  
  int m_pos;  // position of the 'left' eye.  the 'right' eye is m_pos + 1
  
  int m_red;  // RGB components of the color
  int m_green;
  int m_blue;
  
  int m_increment;  // ramp increment - determines blink speed
  int m_repeats;  // not used
  int m_intensity;  // current ramp intensity
  
  public:
  // Constructor - start as inactive
  blinker()
  {
    m_active = false;
  }
  
  // Initiate a blink at the specified pixel position
  // All other blink parameters are randomly generated
  void StartBlink(int pos)
  {
    m_pos = pos;
    
    // Pick a random color - skew toward red/orange/yellow part of the spectrum for extra creepyness
    m_red = random(150, 255);
    m_blue = 0;
    m_green = random(100);
    
    m_repeats += random(1, 3);
    
    // set blink speed and deadtime between blinks
    m_increment = random(1, 6);
    m_deadTime = random(deadTimeMin, deadTimeMax);

    // Mark as active and start at intensity zero
    m_active = true;
    m_intensity = 0;
  }
  
  // Step the state machine:
  void step()
  {
    if (!m_active)
    { 
      // count down the dead-time when the blink is done
      if (m_deadTime > 0)
      {
        m_deadTime--;
      }
      return;
    }
    
    // Increment the intensity
    m_intensity += m_increment;
    if (m_intensity >= 75)  // max out at 75 - then start counting down
    {
      m_increment = -m_increment;
      m_intensity += m_increment;
    }
    if (m_intensity <= 0)
    {
        // make sure pixels all are off
      strip.setPixelColor(m_pos, Color(0,0,0));
      strip.setPixelColor(m_pos+1, Color(0,0,0));
      
      if (--m_repeats <= 0)      // Are we done?
      {
         m_active = false;
      }
      else // no - start to ramp up again
      {
          m_increment = random(1, 5);
      }
      return;
    }
    
    // Generate the color at the current intensity level
    int r =  map(m_red, 0, 255, 0, m_intensity);
    int g =  map(m_green, 0, 255, 0, m_intensity);
    int b =  map(m_blue, 0, 255, 0, m_intensity);
    uint32_t color = Color(r, g, b);
     
    // Write to both 'eyes'
    strip.setPixelColor(m_pos, color);
    strip.setPixelColor(m_pos +1, color);
  }
};

// An array of blinkers - this is the maximum number of concurrently active blinks
blinker blinkers[maxEyes];

// A delay between starting new blinks
int countdown;

void setup() 
{
  Serial.begin(9600);
  // initialize the strip
  strip.begin();
  strip.show();
  
  countdown = 0;
}


void loop()
{
  --countdown;
  for(int i = 0; i < maxEyes; i++)
  {
    // Only start a blink if the countdown is expired and there is an available blinker
    if ((countdown <= 0) && (blinkers[i].m_active == false))
    {
      int newPos = random(0, numPixels - 1);
          
      for(int j = 0; j < maxEyes; j++)
      {
        // avoid active or recently active pixels
        if ((blinkers[j].m_deadTime > 0) && (abs(newPos - blinkers[j].m_pos) < 4))
        {
          Serial.print("-");
          Serial.print(newPos);
          newPos = -1;  // collision - do not start
          break;
        }
      }

      if (newPos >= 0)  // if we have a valid pixel to start with...
      {
       Serial.print(i);
       Serial.print(" Activate - ");
       Serial.println(newPos);
       blinkers[i].StartBlink(newPos);  
       countdown = random(intervalMin, intervalMax);  // random delay to next start
      }
    }
    // step all the state machines
     blinkers[i].step();
  }
  // update the strip
  strip.show();
  delay(10);
}


// Create a 24 bit color value from R,G,B
uint32_t Color(byte r, byte g, byte b)
{
  uint32_t c;
  c = r;
  c <<= 8;
  c |= g;
  c <<= 8;
  c |= b;
  return c;
}

User avatar
phnxfirestorm
 
Posts: 30
Joined: Wed Jan 18, 2012 10:28 pm

Re: How to use random();?

Post by phnxfirestorm »

This is the code I was attempting to use random for:

Code: Select all

void loop() {
  
  // Send a simple pixel chase in...
  colorChase(strip.Color(127,127,127), 20); // white
  colorChase(strip.Color(127,127,0), 20);   // yellow
  colorChase(strip.Color(0,127,0), 20);     // green
  colorChase(strip.Color(100,87,0), 20);     // orange 
  colorChase(strip.Color(100,117,0), 20);     // gold
  colorChase(strip.Color(100,40,0), 20);     // orange
  
  // Fill the entire strip with...
  colorWipe(strip.Color(0, 127,0), 20);     // green
  colorWipe(strip.Color(127,127,0), 20);    // yellow
  colorWipe(strip.Color(127,127,127), 20);    // White
  colorWipe(strip.Color(100,40,0), 20);    // Orange
  
  // Color sparkles
  dither(strip.Color(0,0,0), 5);           // black, fast
  dither(strip.Color(100,40,0), 30);       // orange
  dither(strip.Color(0,0,0), 5);           // black, fast
  dither(strip.Color(0,127,0), 30);       // green, slow
  dither(strip.Color(0,0,0), 5);           // black, fast
  dither(strip.Color(100,117,0), 30);       // gold, slow
  dither(strip.Color(0,0,0), 5);           // black, fast

  // Back-and-forth lights
  scanner(0,127,0, 15);        //green
  scanner (127, 127,127, 17);     //White
  scanner (100 ,87 , 0, 17);     //Orange
  // Wavy ripple effects

  wave(strip.Color(0,127,0), 3, 35);        //Green/white
  wave(strip.Color(100,40,0), 3, 35);        //Green/white
  wave(strip.Color(0,127,0), 3, 35);        //Green/white
  wave(strip.Color(100,127,0), 3, 35);        //Green/white
  wave(strip.Color(0,0,0), 3, 35);        //Green/white
  
  // make a pretty rainbow cycle!
  rainbowCycle(0);  // make it go through the cycle fairly fast
  colorWipe(strip.Color(0,0,0), 20);      // black
  // Clear strip data before start of next effect
  for (int i=0; i < strip.numPixels(); i++) {
    strip.setPixelColor(i, 0);
  }
}

User avatar
adafruit_support_bill
 
Posts: 88091
Joined: Sat Feb 07, 2009 10:11 am

Re: How to use random();?

Post by adafruit_support_bill »

What do you want to randomize? Color? Duration? Sequence?
Any place you use a number in your code, you can replace it with a call to Random. Just be sure to choose an appropriate min and max value so that the result falls in a valid range.

User avatar
phnxfirestorm
 
Posts: 30
Joined: Wed Jan 18, 2012 10:28 pm

Re: How to use random();?

Post by phnxfirestorm »

adafruit_support wrote:What do you want to randomize? Color? Duration? Sequence?
Any place you use a number in your code, you can replace it with a call to Random. Just be sure to choose an appropriate min and max value so that the result falls in a valid range.
I wanted to make the sequence random, I don't like how all of it is goes in order, though I did code it like that. I like it to be random because you never can tell what's next.

User avatar
adafruit_support_bill
 
Posts: 88091
Joined: Sat Feb 07, 2009 10:11 am

Re: How to use random();?

Post by adafruit_support_bill »

So put all the sub-sequences into cases of a big 'switch' statement and select them at random.

Locked
Please be positive and constructive with your questions and comments.

Return to “Arduino”