USBMouse

Dependencies:   USBDevice mbed

Revision:
0:e062501cfe81
diff -r 000000000000 -r e062501cfe81 Accelerometer/Accelerometer.cpp
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Accelerometer/Accelerometer.cpp	Sun Dec 13 10:06:24 2015 +0000
@@ -0,0 +1,55 @@
+#include "Accelerometer.h"
+
+
+#define REG_CTRL_REG_1    0x2A 
+#define REG_OUT_X_MSB     0x01
+#define REG_OUT_Y_MSB     0x03
+#define REG_OUT_Z_MSB     0x05
+
+Accelerometer::Accelerometer(PinName sda, PinName scl, int address) : i2c(sda, scl), addr(address) {
+    // activate the peripheral
+    uint8_t data[2] = {REG_CTRL_REG_1, 0x01};
+    writeRegs(data, 2);
+}
+
+Accelerometer::~Accelerometer() { }
+
+
+float Accelerometer::Acc_X() {
+//divide by 4096 b/c MMA output is 4096 counts per g so this f outputs accelorometer value formatted to g (gravity)
+    return (float(getAccAxis(REG_OUT_X_MSB))/4096.0);
+}
+
+float Accelerometer::Acc_Y() {
+    return (float(getAccAxis(REG_OUT_Y_MSB))/4096.0);
+}
+
+float Accelerometer::Acc_Z() {
+    return (float(getAccAxis(REG_OUT_Z_MSB))/4096.0);
+}
+
+
+
+int16_t Accelerometer::getAccAxis(uint8_t addr) {
+    int16_t acc;
+    uint8_t result[2];
+    readRegs(addr, result, 2);
+
+    acc = (result[0] << 6) | (result[1] >> 2);
+    if (acc > 16383/2)
+        acc -= 16383;
+
+    return acc;
+}
+
+void Accelerometer::readRegs(int addr, uint8_t * data, int len) {
+    char t[1] = {addr};
+    i2c.write(addr, t, 1, true);
+    i2c.read(addr, (char *)data, len);
+}
+
+
+
+void Accelerometer::writeRegs(uint8_t * data, int len) {
+    i2c.write(addr, (char *)data, len);
+}