Library for driving the MMA8452 accelerometer over I2C
Dependents: MMA8452_Test MMA8452_Demo Dualing_Tanks IMU-Controlled_MP3_Player ... more
Here is a simple example:
#include "mbed.h" #include "MMA8452.h" int main() { Serial pc(USBTX,USBRX); pc.baud(115200); double x = 0, y = 0, z = 0; MMA8452 acc(p28, p27, 40000); acc.setBitDepth(MMA8452::BIT_DEPTH_12); acc.setDynamicRange(MMA8452::DYNAMIC_RANGE_4G); acc.setDataRate(MMA8452::RATE_100); while(1) { if(!acc.isXYZReady()) { wait(0.01); continue; } acc.readXYZGravity(&x,&y,&z); pc.printf("Gravities: %lf %lf %lf\r\n",x,y,z); } }
An easy way to test that this actually works is to run the loop above and hold the MMA8452 parallel to the ground along the respective axis (and upsidedown in each axis). You will see 1G on the respective axis and 0G on the others.
Diff: MMA8452.cpp
- Revision:
- 19:4d6cd7140a71
- Parent:
- 17:6e4232c421c0
- Child:
- 20:d55e9d7eb17e
diff -r 27d839e6dc0e -r 4d6cd7140a71 MMA8452.cpp --- a/MMA8452.cpp Wed Mar 05 17:04:04 2014 +0000 +++ b/MMA8452.cpp Thu Mar 06 18:07:43 2014 +0000 @@ -21,6 +21,7 @@ #include "mbed.h" #ifdef MMA8452_DEBUG +// you need to define Serial pc(USBTX,USBRX) somewhere for the below line to make sense extern Serial pc; #define MMA8452_DBG(...) pc.printf(__VA_ARGS__); pc.printf("\r\n"); #else @@ -192,6 +193,39 @@ return readRegister(MMA8452_OUT_X_MSB,dst,readLen); } +int MMA8452::readXRaw(char *dst) { + if(_bitDepth==BIT_DEPTH_UNKNOWN) { + return 1; + } + int readLen = 1; + if(_bitDepth==BIT_DEPTH_12) { + readLen = 2; + } + return readRegister(MMA8452_OUT_X_MSB,dst,readLen); +} + +int MMA8452::readYRaw(char *dst) { + if(_bitDepth==BIT_DEPTH_UNKNOWN) { + return 1; + } + int readLen = 1; + if(_bitDepth==BIT_DEPTH_12) { + readLen = 2; + } + return readRegister(MMA8452_OUT_Y_MSB,dst,readLen); +} + +int MMA8452::readZRaw(char *dst) { + if(_bitDepth==BIT_DEPTH_UNKNOWN) { + return 1; + } + int readLen = 1; + if(_bitDepth==BIT_DEPTH_12) { + readLen = 2; + } + return readRegister(MMA8452_OUT_Z_MSB,dst,readLen); +} + int MMA8452::readXYZCounts(int *x, int *y, int *z) { char buf[6]; if(readXYZRaw((char*)&buf)) { @@ -210,6 +244,23 @@ return 0; } +int readXCount(int *x) { + char buf[2]; + if(readXRaw((char*)&buf)) { + return 1; + } + if(_bitDepth==BIT_DEPTH_12) { + *x = twelveBitToSigned(&buf[0]); + *y = twelveBitToSigned(&buf[2]); + *z = twelveBitToSigned(&buf[4]); + } else { + *x = eightBitToSigned(&buf[0]); + *y = eightBitToSigned(&buf[1]); + *z = eightBitToSigned(&buf[2]); + } + +} + double MMA8452::convertCountToGravity(int count, int countsPerG) { return (double)count/(double)countsPerG; } @@ -356,6 +407,10 @@ return readRegister(addr,dst,1); } +MMA8452::BitDepth MMA8452::getBitDepth() { + return _bitDepth; +} + #ifdef MMA8452_DEBUG void MMA8452::debugRegister(char reg) { // get register value