I'm quite new to this....bought the Arduino last fall but had to put it down for a while [wife and I had a baby]. So when the baby naps, I get to scratch my head and learn this stuff. So for you rookies out there, here is any easy sketch to use an analog 3 axis accelerometer. I'm using the ADXL335
/* Here's a try at making the signal from the accelerometer control the output of a RGB Led
Pin req. - Three pins for Led [output] PWM pins
- three to read the axes of the ADX [input] Analog pins
The Circuit:
RGB Led grounded with a 220 ohm resistor- red lead to pin 11
- green lead to pin 10
- blue lead to pin 9
ADXL335 acclerometer hooked to ground and 3.3 V
- X axis to pin A0
- Z axis to pin A1
- Y axis to pin A2
*/const int redLedPin = 11;
const int greenLedPin = 10;
const int blueLedPin = 9;const int xAxis = A0; //red axis
const int yAxis = A1; //green axis
const int zAxis = A2; //blue axisint sensorX =0;
int sensorY =0;
int sensorZ =0;void setup () {
Serial.begin(9600);pinMode (redLedPin, OUTPUT);
pinMode (greenLedPin, OUTPUT);
pinMode (blueLedPin, OUTPUT);pinMode (xAxis, INPUT);
pinMode (yAxis, INPUT);
pinMode (zAxis, INPUT);
}void loop (){
sensorX = analogRead (xAxis); // read the accelerometer
sensorY = analogRead (yAxis);
sensorZ = analogRead (zAxis);
sensorX = constrain (sensorX, 261, 399); // keep the numbers within a range so it doesn't take huge
sensorY = constrain (sensorY, 261, 399); // jolts to get bright colors
sensorZ = constrain (sensorZ, 264, 400); // the values returned for resting rotation through the range of motion are
// X [266-400] Y [263-395] z [264-395] so 395 is 1gsensorX = map (sensorX, 260, 400, 100, 240); // analogWrite wants values from 0 - 255
sensorY = map (sensorY, 260, 400, 100, 255); // so this keeps the values returned by analogRead (sensorXYZ)
sensorZ = map (sensorZ, 263, 401, 100, 255); // from rolling over and making weird flashesSerial.print(sensorX, DEC ); // this is unnecessary to the operation of the code
Serial.print("\t"); // but it helps to figure out which colors are responding.
Serial.print(sensorY, DEC );
Serial.print("\t");
Serial.println(sensorZ, DEC );analogWrite (redLedPin, sensorX);
analogWrite (greenLedPin, sensorY);
analogWrite (blueLedPin, sensorZ);
delay (20); // don't know if I need this, just trying to
} //get rid of some jitter