Skip to content

Instantly share code, notes, and snippets.

@cryptospectrum
Created April 9, 2013 23:07
Show Gist options
  • Save cryptospectrum/5350181 to your computer and use it in GitHub Desktop.
Save cryptospectrum/5350181 to your computer and use it in GitHub Desktop.
Arduino + accelerometer
/*
Memsic2125
Read the Memsic 2125 two-axis accelerometer. Converts the
pulses output by the 2125 into milli-g's (1/1000 of earth's
gravity) and prints them over the serial connection to the
computer.
The circuit:
* X output of accelerometer to digital pin 2
* Y output of accelerometer to digital pin 3
* +V of accelerometer to +5V
* GND of accelerometer to ground
http://www.arduino.cc/en/Tutorial/Memsic2125
created 6 Nov 2008
by David A. Mellis
modified 30 Aug 2011
by Tom Igoe
modified April 2013
by Mark Aiello
This example code is in the public domain.
*/
// these constants won't change:
const int xPin = 2; // X output of the accelerometer
const int yPin = 3; // Y output of the accelerometer
const int yPinLED = 5; // Y LED output
//const int xPinLED = 6; // X LED output
void setup() {
// initialize serial communications:
Serial.begin(9600);
// initialize the pins connected to the accelerometer
// as inputs:
pinMode(xPin, INPUT);
pinMode(yPin, INPUT);
pinMode(yPinLED, OUTPUT); // sets pin as output
//pinMode(xPinLED, OUTPUT); // sets pin as output
}
void loop() {
// variables to read the pulse widths:
int pulseX, pulseY;
// variables to contain the resulting accelerations
int accelerX, accelerY;
int ledY;
//int ledX;
// read pulse from x- and y-axes:
pulseX = pulseIn(xPin,HIGH);
pulseY = pulseIn(yPin,HIGH);
// convert the pulse width into acceleration
// accelerationX and accelerationY are in milli-g's:
// earth's gravity is 1000 milli-g's, or 1g.
accelerX = ((pulseX / 10) - 500) * 8;
accelerY = 40+((pulseY / 10) - 500) * 8;
//ledX = map(pulseX, 0, 10000, 0, 255);
ledY= map(pulseY, 2000, 5100, 255, 0);
//analogWrite(xPinLED, ledX);
analogWrite(yPinLED, ledY);
//analogWrite(xPinLED, ledX);
Serial.print("AX=");
Serial.print(accelerX);
Serial.print("\t");
Serial.print("AY=");
Serial.print(accelerY);
Serial.print("\t");
Serial.print("X=");
Serial.print(pulseX);
Serial.print("\t");
Serial.print("Y=");
Serial.print(pulseY);
Serial.print("\t");
Serial.println();
delay(100);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment