blob: 1fd74c0dabfd880a73fec824256c661332390623 [file] [log] [blame]
jerrymf1579332013-02-07 01:56:28 +00001/*----------------------------------------------------------------------------*/
2/* Copyright (c) FIRST 2008. All Rights Reserved. */
3/* Open Source Software - may be modified and shared by FRC teams. The code */
4/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
5/*----------------------------------------------------------------------------*/
6
7#include "ADXL345_I2C.h"
8#include "DigitalModule.h"
9#include "NetworkCommunication/UsageReporting.h"
10#include "I2C.h"
11
12const UINT8 ADXL345_I2C::kAddress;
13const UINT8 ADXL345_I2C::kPowerCtlRegister;
14const UINT8 ADXL345_I2C::kDataFormatRegister;
15const UINT8 ADXL345_I2C::kDataRegister;
16const double ADXL345_I2C::kGsPerLSB;
17
18/**
19 * Constructor.
20 *
21 * @param moduleNumber The digital module that the sensor is plugged into (1 or 2).
22 * @param range The range (+ or -) that the accelerometer will measure.
23 */
24ADXL345_I2C::ADXL345_I2C(UINT8 moduleNumber, ADXL345_I2C::DataFormat_Range range)
25 : m_i2c (NULL)
26{
27 DigitalModule *module = DigitalModule::GetInstance(moduleNumber);
28 if (module)
29 {
30 m_i2c = module->GetI2C(kAddress);
31
32 // Turn on the measurements
33 m_i2c->Write(kPowerCtlRegister, kPowerCtl_Measure);
34 // Specify the data format to read
35 m_i2c->Write(kDataFormatRegister, kDataFormat_FullRes | (UINT8)range);
36
37 nUsageReporting::report(nUsageReporting::kResourceType_ADXL345, nUsageReporting::kADXL345_I2C, moduleNumber - 1);
38 }
39}
40
41/**
42 * Destructor.
43 */
44ADXL345_I2C::~ADXL345_I2C()
45{
46 delete m_i2c;
47 m_i2c = NULL;
48}
49
50/**
51 * Get the acceleration of one axis in Gs.
52 *
53 * @param axis The axis to read from.
54 * @return Acceleration of the ADXL345 in Gs.
55 */
56double ADXL345_I2C::GetAcceleration(ADXL345_I2C::Axes axis)
57{
58 INT16 rawAccel = 0;
59 if(m_i2c)
60 {
61 m_i2c->Read(kDataRegister + (UINT8)axis, sizeof(rawAccel), (UINT8 *)&rawAccel);
62
63 // Sensor is little endian... swap bytes
64 rawAccel = ((rawAccel >> 8) & 0xFF) | (rawAccel << 8);
65 }
66 return rawAccel * kGsPerLSB;
67}
68
69/**
70 * Get the acceleration of all axes in Gs.
71 *
72 * @return Acceleration measured on all axes of the ADXL345 in Gs.
73 */
74ADXL345_I2C::AllAxes ADXL345_I2C::GetAccelerations()
75{
76 AllAxes data = {0.0};
77 INT16 rawData[3];
78 if (m_i2c)
79 {
80 m_i2c->Read(kDataRegister, sizeof(rawData), (UINT8*)rawData);
81
82 // Sensor is little endian... swap bytes
83 for (INT32 i=0; i<3; i++)
84 {
85 rawData[i] = ((rawData[i] >> 8) & 0xFF) | (rawData[i] << 8);
86 }
87
88 data.XAxis = rawData[0] * kGsPerLSB;
89 data.YAxis = rawData[1] * kGsPerLSB;
90 data.ZAxis = rawData[2] * kGsPerLSB;
91 }
92 return data;
93}
94