by Rob Toulson and Tim Wilmshurst from textbook "Fast and Effective Embedded Systems Design: Applying the ARM mbed"

Dependencies:   mbed

Revision:
0:371be129802f
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/main.cpp	Mon Oct 15 21:25:27 2012 +0000
@@ -0,0 +1,41 @@
+/*Program Example 7.4: Reads values from accelerometer through SPI, and outputs 
+continuously to terminal screen.
+*/
+
+#include "mbed.h"
+SPI acc(p11,p12,p13);            // set up SPI interface on pins 11,12,13
+DigitalOut cs(p14);              // use pin 14 as chip select      
+Serial pc(USBTX, USBRX);         // set up USB interface to host terminal
+char buffer[6];                  //raw data array type char
+int16_t data[3];                 // 16-bit twos-complement integer data
+float x, y, z;                   // floating point data, to be displayed on-screen
+
+int main() {
+  cs=1;                        //initially ADXL345 is not activated
+  acc.format(8,3);             // 8 bit data, Mode 3
+  acc.frequency(2000000);      // 2MHz clock rate
+  cs=0;                        //select the device
+  acc.write(0x31);             // data format register
+  acc.write(0x0B);             // format +/-16g, 0.004g/LSB
+  cs=1;                        //end of transmission
+  cs=0;                        //start a new transmission
+  acc.write(0x2D);             // power ctrl register
+  acc.write(0x08);             // measure mode
+  cs=1;                        //end of transmission
+  while (1) {                  // infinite loop
+    wait(0.2);
+    cs=0;                      //start a transmission
+    acc.write(0x80|0x40|0x32);   // RW bit high, MB bit high, plus address
+    for (int i = 0;i<=5;i++) {
+      buffer[i]=acc.write(0x00);       // read back 6 data bytes
+    }
+    cs=1;                      //end of transmission
+    data[0] = buffer[1]<<8 | buffer[0];  // combine MSB and LSB
+    data[1] = buffer[3]<<8 | buffer[2];
+    data[2] = buffer[5]<<8 | buffer[4];       
+    x=0.004*data[0]; y=0.004*data[1]; z=0.004*data[2]; // convert to float, 
+                                                       //actual g value
+    pc.printf("x = %+1.2fg\t y = %+1.2fg\t z = %+1.2fg\n\r", x, y,z); //print 
+  }
+}
+