Thursday, October 29, 2009

Here is some code to start working with the accelerometer. It was taken from here, and edited to work with the Arduino Mega.


/*
Accelerometer Reader

Reads the X and Y of a 3-axis accelerometer

The accelerometer, an ADXL330 from Sparkfun, is attached
to analogs 1 through 3. Analog pins 0, 4, and 5
are used as digital I/O pins in this case, as follows:
Analog 0 = Digital 14 = HIGH (accelerometer self test)
Analog 4 = Digital 18 = LOW (accelerometer ground)
Analog 5 = Digital 19 = HIGH (accelerometer Vin)

Sends serial readings in this format:
X, Y\r\n

created 19 Sep 2008
by Tom Igoe

last modified 28 Oct 2008
by Rory Nugent

Recent Changes:
Removed calculation of the max and min, sends only X-axis and Y-axis values, and
configured a basic wait period after boot to wait for Processing and to throw out
all readings during this period.
*/

int accelReading = 0;

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

pinMode(13,OUTPUT); //on board LED

// set up Analog 0, 4, and 5 to be
// digital I/O (14, 18, and 19, respectively):
pinMode(54, OUTPUT); //analog pin 0
pinMode(58, OUTPUT); //analog pin 4
pinMode(59, OUTPUT); //analog pin 5

// set pins appropriately for accelerometer's needs:
digitalWrite(54, HIGH); // acc. self test
digitalWrite(58, LOW); // acc. ground
digitalWrite(59, HIGH); // acc. power

digitalWrite(13,HIGH); //on board LED

// send a byte out the serial port until
// you get one back in to initialize
// call-and-response serial communication:
while (Serial.available() <=0) {
// take readings of the accelerometer while you wait for a call-and-response
// doing this seems to clear out any initial garbage and settle down the ADC
for (int channel = 1; channel < 4; channel++) {
analogRead(channel);
delay(10);
}
Serial.print("\n");
}

digitalWrite(13,LOW);
}

void loop() {
// only send if you have an incoming serial byte:
if (Serial.available()) {
// read and print the x-axis value from the accelerometer
Serial.print(analogRead(3));

// print a delimiter
Serial.print(",");

//read and print the y-axis from the accelerometer
Serial.print(analogRead(2));

// print carriage return and newline:
Serial.println();

Serial.flush();
}
}

I plan on editting this heavily, but it shows how you can use the analog pins as digital pins, but also uses the analog pins to power the accelerometer. This will simplify wiring. The code waits for a character to be sent over the serial port, which really isn't what I would be using it for, but it is a neat method.

No comments: