First

Dependencies:   UniGraphic mbed

Committer:
asloop18
Date:
Thu Jan 14 21:35:29 2016 +0000
Revision:
3:824764571657
Child:
5:98ad3701ec24
Acc base code added

Who changed what in which revision?

UserRevisionLine numberNew contents of line
asloop18 3:824764571657 1 /* Program 7.4: Read ADXL345 accelerometer through SPI.
asloop18 3:824764571657 2 Outputs continuously to terminal
asloop18 3:824764571657 3 */
asloop18 3:824764571657 4
asloop18 3:824764571657 5 #include "mbed.h"
asloop18 3:824764571657 6
asloop18 3:824764571657 7 SPI acc(p11,p12,p13); //Set up SPI MOSI, MISO, SCL
asloop18 3:824764571657 8 DigitalOut cs(p14); //set up chip select
asloop18 3:824764571657 9 Serial pc(USBTX, USBRX);
asloop18 3:824764571657 10 char buffer[6]; //raw filler data
asloop18 3:824764571657 11 int16_t data[3]; //16bit twos-compliment integer data
asloop18 3:824764571657 12 float x,y,z; //set up floats for values to display
asloop18 3:824764571657 13
asloop18 3:824764571657 14 int main(){
asloop18 3:824764571657 15 cs=1; //initially off
asloop18 3:824764571657 16 acc.format(8,3); //8bit, mode 3
asloop18 3:824764571657 17 acc.frequency(2000000); //2MHz
asloop18 3:824764571657 18 cs=0; //select
asloop18 3:824764571657 19 acc.write(0x31); //data format register
asloop18 3:824764571657 20 acc.write(0x0B); //+/-16g, 0.004g sensitivity
asloop18 3:824764571657 21 cs=1; //end transmission
asloop18 3:824764571657 22 cs=0; //start new transmission
asloop18 3:824764571657 23 acc.write(0x2D); //power mode = measure
asloop18 3:824764571657 24 acc.write(0x08);
asloop18 3:824764571657 25 cs=1;
asloop18 3:824764571657 26
asloop18 3:824764571657 27
asloop18 3:824764571657 28 while(1){
asloop18 3:824764571657 29 wait(0.2);
asloop18 3:824764571657 30 cs=0;
asloop18 3:824764571657 31 acc.write(0x80|0x40|0x32); //RW bit high, MB bit high, address
asloop18 3:824764571657 32 for (int i=0;i<=5;i++){buffer[i]=acc.write(0x00);} //read 6bytes
asloop18 3:824764571657 33 cs=1;
asloop18 3:824764571657 34 data[0]=buffer[1]<<8|buffer[0];
asloop18 3:824764571657 35 data[1]=buffer[3]<<8|buffer[2]; //combine MSB and LSB
asloop18 3:824764571657 36 data[2]=buffer[5]<<8|buffer[4];
asloop18 3:824764571657 37 x=0.004*data[0]; y=0.004*data[1]; z=0.004*data[2]; //convert to float, actual g value
asloop18 3:824764571657 38 pc.printf("x = %+1.2fg\t y = %+1.2fg\t z = %+1.2fg\n\r", x,y,z);
asloop18 3:824764571657 39 }
asloop18 3:824764571657 40 }