# Trouble with an RGB LED and accelorometer

here is a video of the project, I have two RGB LEDs reading accelerometer values of XYZ.

Here is a video of the flickering that happens in certain positions. These are major Hue shifts not just jumpy readings from a sensitive accelerometer.http://vimeo.com/4400183

here is the code that I am running.

``````#define AVARAGE_READINGS 10

int Rled = 9;
int Gled = 10;
int Bled = 11;
int Xpin = 0;
int Ypin = 1;
int Zpin = 2;
int Rled2 = 3;
int Gled2 = 5;
int Bled2 = 6;

void setup()
{
Serial.begin(9600);

pinMode(Rled, OUTPUT);
pinMode(Gled, OUTPUT);
pinMode(Bled, OUTPUT);
pinMode(Rled2, OUTPUT);
pinMode(Gled2, OUTPUT);
pinMode(Bled2, OUTPUT);
}

void loop()
{
x /= 2;
y /= 2;
z /= 2;
}

x = map(x, 268, 405, 0, 255);
y = map(y, 270, 420, 0, 255);
z = map(z, 354, 450, 0, 255);

Serial.print("X ");
Serial.print(x);
Serial.print("       Y ");
Serial.print(y);
Serial.print("       Z");
Serial.println(z);

analogWrite(Rled, x);
analogWrite(Gled, y);
analogWrite(Bled, z);
analogWrite(Rled2, x);
analogWrite(Gled2, y);
analogWrite(Bled2, z);
}
``````

You are not doing the averaging correctly. What you are doing is a running average. This means that that last sample taken amounts for 50% of the total reading.

Take all the readings and add them up first, then divide by the number of samples you have taken.

``````1 4 23 15 26 47 23 34 4

Running Average: 17,75
Regular Average: 19,6
``````

Running Average Pros:

• Resource friendly
• Easy to understand (no arrays==easier for beginners)

Running Average Cons:

• Does not provide a ‘real’ average.
• Does not maintain a ‘history’ or a current value. [not this code that is]

I doubt this being the source of the error/flicker.

You could try this:
[UNTESTED CODE]

int Rled = 9;
int Gled = 10;
int Bled = 11;
int Xpin = 0;
int Ypin = 1;
int Zpin = 2;
int Rled2 = 3;
int Gled2 = 5;
int Bled2 = 6;

void setup()
{
Serial.begin(9600);

pinMode(Rled, OUTPUT);
pinMode(Gled, OUTPUT);
pinMode(Bled, OUTPUT);
pinMode(Rled2, OUTPUT);
pinMode(Gled2, OUTPUT);
pinMode(Bled2, OUTPUT);
}

void loop()
{
* }_
_ x = map(x, 268, 405, 0, 255);
y = map(y, 270, 420, 0, 255);
z = map(z, 354, 450, 0, 255);
Serial.print(“X “);
Serial.print(x);
Serial.print(” Y “);
Serial.print(y);
Serial.print(” Z”);
Serial.println(z);
analogWrite(Rled, x);
analogWrite(Gled, y);
analogWrite(Bled, z);
analogWrite(Rled2, x);
analogWrite(Gled2, y);
analogWrite(Bled2, z);
}
//average an array*
unsigned int average(int values[],byte length){
* unsigned int average = 0;
for (byte i=0; i<length; i++){
average += values;
}
average /= length;
return average;
}
[/quote]
[/edit]*_

Too complex you don’t need arrays just do:-

``````{
xValue =  yValue =  zValue = 0;
}