Skip to content

Instantly share code, notes, and snippets.

@ss23
Created November 15, 2014 12:42
Show Gist options
  • Save ss23/6ce5bc194f9730a64add to your computer and use it in GitHub Desktop.
Save ss23/6ce5bc194f9730a64add to your computer and use it in GitHub Desktop.
#include <Wire.h>
#define ACC (0x53) //ADXL345 ACC address
#define A_TO_READ (8) //num of bytes we are going to read each time (two bytes for each axis)
void setup() {
Serial.begin(9600); // This is for our console
Wire.begin(); // For the accel
delay(3000);
initAcc();
Serial.write("Beginning");
}
void loop() {
char str[512];
int16_t acc[3];
getAccelerometerData(acc);
sprintf(str, "%hd %hd %hd %hd\r\n", acc[0], acc[1], acc[2], acc[3]);
Serial.print(str);
delay(20);
}
//---------------- Functions
//Writes val to address register on ACC
void writeTo(int DEVICE, byte address, byte val) {
Wire.beginTransmission(DEVICE); //start transmission to ACC
Wire.write(address); // send register address
Wire.write(val); // send value to write
Wire.endTransmission(); //end transmission
}
//reads num bytes starting from address register on ACC in to buff array
void readFrom(int DEVICE, byte address, int num, byte buff[]) {
Wire.beginTransmission(DEVICE); //start transmission to ACC
Wire.write(address); //sends address to read from
Wire.endTransmission(); //end transmission
Wire.beginTransmission(DEVICE); //start transmission to ACC
Wire.requestFrom(DEVICE, num); // request 6 bytes from ACC
int i = 0;
while(Wire.available()) //ACC may send less than requested (abnormal)
{
buff[i] = Wire.read(); // receive a byte
i++;
}
Wire.endTransmission(); //end transmission
}
void initAcc() {
//Turning on the ADXL345
writeTo(ACC, 0x2D, 0);
writeTo(ACC, 0x2D, 16);
writeTo(ACC, 0x2D, 8);
//by default the device is in +-2g range reading
}
void getAccelerometerData(int16_t * result) {
//int regAddress = 0x32; //first axis-acceleration-data register on the ADXL345
// FUCK THa POLICe, LETS MAKE OUR OWN ADRESS
int regAddress = 0x30;
byte buff[A_TO_READ];
readFrom(ACC, regAddress, A_TO_READ, buff); //read the acceleration data from the ADXL345
//each axis reading comes in 10 bit resolution, ie 2 bytes. Least Significat Byte first!!
//thus we are converting both bytes in to one int
result[0] = (((int)buff[1]) << 8) | buff[0];
result[1] = (((int)buff[3])<< 8) | buff[2];
result[2] = (((int)buff[5]) << 8) | buff[4];
result[3] = (((int)buff[6]) << 8) | buff[7];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment