LED fade using Accelerometer

For an LED project, i need to make a light board that fades from one color to another when tilted left or right. I’m going to be programming around 200 LEDs, and I’m going to be using an ADXL322 accelerometer. Can anyone help with programming? I’m an ambitious student with only a couple of weeks to complete this and I’m new to this.

I found this code for fading colors, in the hopes that it can be applied to an accelerometer:
/*

  • Code for cross-fading 3 LEDs, red, green and blue (RGB)
  • To create fades, you need to do two things:
    1. Describe the colors you want to be displayed
    1. List the order you want them to fade in
  • DESCRIBING A COLOR:
  • A color is just an array of three percentages, 0-100,
  • controlling the red, green and blue LEDs
  • Red is the red LED at full, blue and green off
  • int red = { 100, 0, 0 }
  • Dim white is all three LEDs at 30%
  • int dimWhite = {30, 30, 30}
  • etc.
  • Some common colors are provided below, or make your own
  • LISTING THE ORDER:
  • In the main part of the program, you need to list the order
  • you want to colors to appear in, e.g.
  • crossFade(red);
  • crossFade(green);
  • crossFade(blue);
  • Those colors will appear in that order, fading out of
  • one color and into the next
  • In addition, there are 5 optional settings you can adjust:
    1. The initial color is set to black (so the first color fades in), but
  • you can set the initial color to be any other color
    1. The internal loop runs for 1020 interations; the ‘wait’ variable
  • sets the approximate duration of a single crossfade. In theory,
  • a ‘wait’ of 10 ms should make a crossFade of ~10 seconds. In
  • practice, the other functions the code is performing slow this
  • down to ~11 seconds on my board. YMMV.
    1. If ‘repeat’ is set to 0, the program will loop indefinitely.
  • if it is set to a number, it will loop that number of times,
  • then stop on the last color in the sequence. (Set ‘return’ to 1,
  • and make the last color black if you want it to fade out at the end.)
    1. There is an optional ‘hold’ variable, which pasues the
  • program for ‘hold’ milliseconds when a color is complete,
  • but before the next color starts.
    1. Set the DEBUG flag to 1 if you want debugging output to be
  • sent to the serial monitor.
  • The internals of the program aren’t complicated, but they
  • are a little fussy – the inner workings are explained
  • below the main loop.
  • April 2007, Clay Shirky clay.shirky@nyu.edu
    */

// Output
int redPin = 9; // Red LED, connected to digital pin 9
int grnPin = 10; // Green LED, connected to digital pin 10
int bluPin = 11; // Blue LED, connected to digital pin 11

// Color arrays
int black[3] = { 0, 0, 0 };
int white[3] = { 100, 100, 100 };
int red[3] = { 100, 0, 0 };
int green[3] = { 0, 100, 0 };
int blue[3] = { 0, 0, 100 };
int yellow[3] = { 40, 95, 0 };
int dimWhite[3] = { 30, 30, 30 };
// etc.

// Set initial color
int redVal = black[0];
int grnVal = black[1];
int bluVal = black[2];

int wait = 10; // 10ms internal crossFade delay; increase for slower fades
int hold = 0; // Optional hold when a color is complete, before the next crossFade
int DEBUG = 1; // DEBUG counter; if set to 1, will write values back via serial
int loopCount = 60; // How often should DEBUG report?
int repeat = 3; // How many times should we loop before stopping? (0 for no stop)
int j = 0; // Loop counter for repeat

// Initialize color variables
int prevR = redVal;
int prevG = grnVal;
int prevB = bluVal;

// Set up the LED outputs
void setup()
{
pinMode(redPin, OUTPUT); // sets the pins as output
pinMode(grnPin, OUTPUT);
pinMode(bluPin, OUTPUT);

if (DEBUG) { // If we want to see values for debugging…
Serial.begin(9600); // …set up the serial ouput
}
}

// Main program: list the order of crossfades
void loop()
{
crossFade(red);
crossFade(green);
crossFade(blue);
crossFade(yellow);

if (repeat) { // Do we loop a finite number of times?
j += 1;
if (j >= repeat) { // Are we there yet?
exit(j); // If so, stop.
}
}
}

/* BELOW THIS LINE IS THE MATH – YOU SHOULDN’T NEED TO CHANGE THIS FOR THE BASICS
*

  • The program works like this:
  • Imagine a crossfade that moves the red LED from 0-10,
  • the green from 0-5, and the blue from 10 to 7, in
  • ten steps.
  • We’d want to count the 10 steps and increase or
  • decrease color values in evenly stepped increments.
  • Imagine a + indicates raising a value by 1, and a -
  • equals lowering it. Our 10 step fade would look like:
  • 1 2 3 4 5 6 7 8 9 10
  • R + + + + + + + + + +
  • G + + + + +
  • B - - -
  • The red rises from 0 to 10 in ten steps, the green from
  • 0-5 in 5 steps, and the blue falls from 10 to 7 in three steps.
  • In the real program, the color percentages are converted to
  • 0-255 values, and there are 1020 steps (255*4).
  • To figure out how big a step there should be between one up- or
  • down-tick of one of the LED values, we call calculateStep(),
  • which calculates the absolute gap between the start and end values,
  • and then divides that gap by 1020 to determine the size of the step
  • between adjustments in the value.
    */

int calculateStep(int prevValue, int endValue) {
int step = endValue - prevValue; // What’s the overall gap?
if (step) { // If its non-zero,
step = 1020/step; // divide by 1020
}
return step;
}

/* The next function is calculateVal. When the loop value, i,

  • reaches the step size appropriate for one of the
  • colors, it increases or decreases the value of that color by 1.
  • (R, G, and B are each calculated separately.)
    */

int calculateVal(int step, int val, int i) {

if ((step) && i % step == 0) { // If step is non-zero and its time to change a value,
if (step > 0) { // increment the value if step is positive…
val += 1;
}
else if (step < 0) { // …or decrement it if step is negative
val -= 1;
}
}
// Defensive driving: make sure val stays in the range 0-255
if (val > 255) {
val = 255;
}
else if (val < 0) {
val = 0;
}
return val;
}

/* crossFade() converts the percentage colors to a

  • 0-255 range, then loops 1020 times, checking to see if
  • the value needs to be updated each time, then writing
  • the color values to the correct pins.
    */

void crossFade(int color[3]) {
// Convert to 0-255
int R = (color[0] * 255) / 100;
int G = (color[1] * 255) / 100;
int B = (color[2] * 255) / 100;

int stepR = calculateStep(prevR, R);
int stepG = calculateStep(prevG, G);
int stepB = calculateStep(prevB, B);

for (int i = 0; i <= 1020; i++) {
redVal = calculateVal(stepR, redVal, i);
grnVal = calculateVal(stepG, grnVal, i);
bluVal = calculateVal(stepB, bluVal, i);

analogWrite(redPin, redVal); // Write current values to LED pins
analogWrite(grnPin, grnVal);
analogWrite(bluPin, bluVal);

delay(wait); // Pause for ‘wait’ milliseconds before resuming the loop

if (DEBUG) { // If we want serial output, print it at the
if (i == 0 or i % loopCount == 0) { // beginning, and every loopCount times
Serial.print(“Loop/RGB: #”);
Serial.print(i);
Serial.print(" | “);
Serial.print(redVal);
Serial.print(” / “);
Serial.print(grnVal);
Serial.print(” / ");
Serial.println(bluVal);
}
DEBUG += 1;
}
}
// Update current values for next loop
prevR = redVal;
prevG = grnVal;
prevB = bluVal;
delay(hold); // Pause for optional ‘wait’ milliseconds before resuming the loop
}

I'm an ambitious student with only a couple of weeks to complete this and I'm new to this.

Ambitious and "waited until the last minute" hardly seem to go together.

I'm going to be programming around 200 LEDs

How? You have some plan for how to connect 200 LEDs to one Arduino? You have a plan for how to power them all?

and I'm going to be using an ADXL322 accelerometer.

You know how to connect it? How to read data from it?

Can anyone help with programming?

Sure. Post your code, describe what is working right, and what is not, and we'll help you fix it. Oh, you mean write it for you? Hey, you're the ambition student. Better get cracking.

sorry, i'll post the accelerometer code. I was hoping for some pointers on how to put the codes together, not to write the code.

I'm going to use a multi-plexing chip hooked up to the arduino to use more LEDs

also, I was only recently assigned the project, and don't have much time because we have a few projects only a quarter to complete them. I'm willing to work day and night on this. told you I'm new, so i appreciate helpful responses

code for the ADXL:

/* ADXL3xx

Reads an Analog Devices ADXL3xx accelerometer and communicates the acceleration to the computer. The pins used are designed to be easily compatible with the breakout boards from Sparkfun, available from: http://www.sparkfun.com/commerce/categories.php?c=80

http://www.arduino.cc/en/Tutorial/ADXL3xx

The circuit: analog 0: accelerometer self test analog 1: z-axis analog 2: y-axis analog 3: x-axis analog 4: ground analog 5: vcc

created 2 Jul 2008 by David A. Mellis modified 4 Sep 2010 by Tom Igoe

This example code is in the public domain.

*/

// these constants describe the pins. They won't change: const int groundpin = 18; // analog input pin 4 -- ground const int powerpin = 19; // analog input pin 5 -- voltage const int xpin = A3; // x-axis of the accelerometer const int ypin = A2; // y-axis const int zpin = A1; // z-axis (only on 3-axis models)

void setup() { // initialize the serial communications: Serial.begin(9600);

// Provide ground and power by using the analog inputs as normal // digital pins. This makes it possible to directly connect the // breakout board to the Arduino. If you use the normal 5V and // GND pins on the Arduino, you can remove these lines. pinMode(groundpin, OUTPUT); pinMode(powerpin, OUTPUT); digitalWrite(groundpin, LOW); digitalWrite(powerpin, HIGH); }

void loop() { // print the sensor values: Serial.print(analogRead(xpin)); // print a tab between values: Serial.print("\t"); Serial.print(analogRead(ypin)); // print a tab between values: Serial.print("\t"); Serial.print(analogRead(zpin)); Serial.println(); // delay before next reading: delay(100);

as for connecting it, here's a link to the schematic

http://arduino.cc/en/uploads/Tutorial/ADXL3XX_2_schem.png

There's a limit 0n the number of characters in a post. You code post exceeded that limit, so it was truncated. Also, there is a # button on the top row that puts the posted code in a gray box with scroll bars. Please use that button in the future.

The first step is to actually connect the accelerometer, and see that it works. Then, you will have some varying values.

Next, you need to decide how those values will affect the color of the LEDs.

Finally, you need to decide how you will connect and power all the LEDs.

If this is a school project, the focus is either on programming, in which case driving 10 LEDs is as easy or difficult as driving 200 of them. If it's a hardware oriented class, the programming is less important than proper functioning of the hardware.

So, what kind of class is it?

ok thanks, I’ll make sure to do that next time.

It’s actually neither. The class is Intro to Electronic Intermedia, which is an art studio, and we’re learning programming as we are working on our projects. kinda half and half.

As far as I know we’re only using bread boards to connect the LEDs, although I’m the only one in the class who’s also using a multiplexing chip.
here’s the led code again

/*
* Code for cross-fading 3 LEDs, red, green and blue (RGB) 
* To create fades, you need to do two things: 
*  1. Describe the colors you want to be displayed
*  2. List the order you want them to fade in
*
* DESCRIBING A COLOR:
* A color is just an array of three percentages, 0-100, 
*  controlling the red, green and blue LEDs
*
* Red is the red LED at full, blue and green off
*   int red = { 100, 0, 0 }
* Dim white is all three LEDs at 30%
*   int dimWhite = {30, 30, 30}
* etc.
*
* Some common colors are provided below, or make your own
* 
* LISTING THE ORDER:
* In the main part of the program, you need to list the order 
*  you want to colors to appear in, e.g.
*  crossFade(red);
*  crossFade(green);
*  crossFade(blue);
*
* Those colors will appear in that order, fading out of 
*    one color and into the next  
*
* In addition, there are 5 optional settings you can adjust:
* 1. The initial color is set to black (so the first color fades in), but 
*    you can set the initial color to be any other color
* 2. The internal loop runs for 1020 interations; the 'wait' variable
*    sets the approximate duration of a single crossfade. In theory, 
*    a 'wait' of 10 ms should make a crossFade of ~10 seconds. In 
*    practice, the other functions the code is performing slow this 
*    down to ~11 seconds on my board. YMMV.
* 3. If 'repeat' is set to 0, the program will loop indefinitely.
*    if it is set to a number, it will loop that number of times,
*    then stop on the last color in the sequence. (Set 'return' to 1, 
*    and make the last color black if you want it to fade out at the end.)
* 4. There is an optional 'hold' variable, which pasues the 
*    program for 'hold' milliseconds when a color is complete, 
*    but before the next color starts.
* 5. Set the DEBUG flag to 1 if you want debugging output to be
*    sent to the serial monitor.
*
*    The internals of the program aren't complicated, but they
*    are a little fussy -- the inner workings are explained 
*    below the main loop.
*
* April 2007, Clay Shirky <clay.shirky@nyu.edu> 
*/ 

// Output
int redPin = 9;   // Red LED,   connected to digital pin 9
int grnPin = 10;  // Green LED, connected to digital pin 10
int bluPin = 11;  // Blue LED,  connected to digital pin 11

// Color arrays
int black[3]  = { 0, 0, 0 };
int white[3]  = { 100, 100, 100 };
int red[3]    = { 100, 0, 0 };
int green[3]  = { 0, 100, 0 };
int blue[3]   = { 0, 0, 100 };
int yellow[3] = { 40, 95, 0 };
int dimWhite[3] = { 30, 30, 30 };
// etc.

// Set initial color
int redVal = black[0];
int grnVal = black[1]; 
int bluVal = black[2];

int wait = 10;      // 10ms internal crossFade delay; increase for slower fades
int hold = 0;       // Optional hold when a color is complete, before the next crossFade
int DEBUG = 1;      // DEBUG counter; if set to 1, will write values back via serial
int loopCount = 60; // How often should DEBUG report?
int repeat = 3;     // How many times should we loop before stopping? (0 for no stop)
int j = 0;          // Loop counter for repeat

// Initialize color variables
int prevR = redVal;
int prevG = grnVal;
int prevB = bluVal;

// Set up the LED outputs
void setup()
{
  pinMode(redPin, OUTPUT);   // sets the pins as output
  pinMode(grnPin, OUTPUT);   
  pinMode(bluPin, OUTPUT); 

  if (DEBUG) {           // If we want to see values for debugging...
    Serial.begin(9600);  // ...set up the serial ouput 
  }
}

// Main program: list the order of crossfades
void loop()
{
  crossFade(red);
  crossFade(green);
  crossFade(blue);
  crossFade(yellow);

  if (repeat) { // Do we loop a finite number of times?
    j += 1;
    if (j >= repeat) { // Are we there yet?
      exit(j);         // If so, stop.
    }
  }
}

/* BELOW THIS LINE IS THE MATH -- YOU SHOULDN'T NEED TO CHANGE THIS FOR THE BASICS
* 
* The program works like this:
* Imagine a crossfade that moves the red LED from 0-10, 
*   the green from 0-5, and the blue from 10 to 7, in
*   ten steps.
*   We'd want to count the 10 steps and increase or 
*   decrease color values in evenly stepped increments.
*   Imagine a + indicates raising a value by 1, and a -
*   equals lowering it. Our 10 step fade would look like:
* 
*   1 2 3 4 5 6 7 8 9 10
* R + + + + + + + + + +
* G   +   +   +   +   +
* B     -     -     -
* 
* The red rises from 0 to 10 in ten steps, the green from 
* 0-5 in 5 steps, and the blue falls from 10 to 7 in three steps.
* 
* In the real program, the color percentages are converted to 
* 0-255 values, and there are 1020 steps (255*4).
* 
* To figure out how big a step there should be between one up- or
* down-tick of one of the LED values, we call calculateStep(), 
* which calculates the absolute gap between the start and end values, 
* and then divides that gap by 1020 to determine the size of the step  
* between adjustments in the value.
*/

int calculateStep(int prevValue, int endValue) {
  int step = endValue - prevValue; // What's the overall gap?
  if (step) {                      // If its non-zero, 
    step = 1020/step;              //   divide by 1020
  } 
  return step;
}

/* The next function is calculateVal. When the loop value, i,
*  reaches the step size appropriate for one of the
*  colors, it increases or decreases the value of that color by 1. 
*  (R, G, and B are each calculated separately.)
*/

int calculateVal(int step, int val, int i) {

  if ((step) && i % step == 0) { // If step is non-zero and its time to change a value,
    if (step > 0) {              //   increment the value if step is positive...
      val += 1;           
    } 
    else if (step < 0) {         //   ...or decrement it if step is negative
      val -= 1;
    } 
  }
  // Defensive driving: make sure val stays in the range 0-255
  if (val > 255) {
    val = 255;
  } 
  else if (val < 0) {
    val = 0;
  }
  return val;
}

/* crossFade() converts the percentage colors to a 
*  0-255 range, then loops 1020 times, checking to see if  
*  the value needs to be updated each time, then writing
*  the color values to the correct pins.
*/

void crossFade(int color[3]) {
  // Convert to 0-255
  int R = (color[0] * 255) / 100;
  int G = (color[1] * 255) / 100;
  int B = (color[2] * 255) / 100;

  int stepR = calculateStep(prevR, R);
  int stepG = calculateStep(prevG, G); 
  int stepB = calculateStep(prevB, B);

  for (int i = 0; i <= 1020; i++) {
    redVal = calculateVal(stepR, redVal, i);
    grnVal = calculateVal(stepG, grnVal, i);
    bluVal = calculateVal(stepB, bluVal, i);

    analogWrite(redPin, redVal);   // Write current values to LED pins
    analogWrite(grnPin, grnVal);      
    analogWrite(bluPin, bluVal); 

    delay(wait); // Pause for 'wait' milliseconds before resuming the loop

    if (DEBUG) { // If we want serial output, print it at the 
      if (i == 0 or i % loopCount == 0) { // beginning, and every loopCount times
        Serial.print("Loop/RGB: #");
        Serial.print(i);
        Serial.print(" | ");
        Serial.print(redVal);
        Serial.print(" / ");
        Serial.print(grnVal);
        Serial.print(" / ");  
        Serial.println(bluVal); 
      } 
      DEBUG += 1;
    }
  }
  // Update current values for next loop
  prevR = redVal; 
  prevG = grnVal; 
  prevB = bluVal;
  delay(hold); // Pause for optional 'wait' milliseconds before resuming the loop
}

So, you have some code that fades LEDs in a complex way.

Perhaps you should start with something simpler. Determine the range of values, for each of the 3 axes, that you get as you move the accelerometer. Assign each axis to a separate color. Moving the accelerometer in the X axis controls the red value, while the Y axis controls blue and Z controls green.

Simply map the actual X value using the range of X values possible and the range of R values that you want to see. Do the same for Y/G and Z/B. Then, light up one or more LEDs with the resulting mapped values.

Once this works, you can extend it control multiple LEDs.

Thanks for the help! I'll be sure to post images when i complete it