Sunday, May 19, 2013

[Weekend Hack] Arduino + ADXL3xx Accelerometer

Do you remember I once told you I have an arduino uno board? I don't have enough accessories; a LED, a push button, 10 jumper wires, a  breadboard and an ADXL3xx accelerometer chip. Last weekend, I tried out the LED and the push button. 
This weekend, I set out to explore how best I can use my accelerometer chip. Though I could not understand most of the resources found, I resorted to this tutorial on the arduino site.  I wired up the chip and LED nicely to the breadboard and powered it with  5V. All I knew was, I will be receiving values from 0 to 1023 (0 at 0V and 1023 at 5V). I set my LED up to blink when the value of the x-axis exceeds 512.

board setup

I turned the board around, placed my phone underneath and introduced vibration to it. Luckily for me, it worked, seeing different values pop up. See my codes below:


// these constants describe the pins. They won't change:
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)
const int x_max = 512;
int ledPin = 8; //pin for led
//setup
void setup(){
pinMode(ledPin, OUTPUT); // set LED on output mode
Serial.begin(9600); //start serial communication
}
//loop
void loop(){
//read values from x, y, z pins
int xVal = analogRead(xpin);
int yVal = analogRead(ypin);
int zVal = analogRead(zpin);
//compare values to x_max and trigger LED Blink
if(xVal > x_max){
digitalWrite(ledPin, LOW);
delay(100);
digitalWrite(ledPin, HIGH);
delay(100);
} else{
digitalWrite(ledPin, LOW);
}
//print sensor values
Serial.print(xVal);
Serial.print("\t");
Serial.print(yVal);
Serial.print("\t");
Serial.print(zVal);
Serial.println();
delay(1000); //wait a second
}


Review and send in your comments.

No comments:

Post a Comment