Simon Barker / Mbed 2 deprecated ADXL345

Dependencies:   mbed

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers ADXL345sb.cpp Source File

ADXL345sb.cpp

00001 #include "ADXL345sb.h"
00002 
00003 ADXL345sb::ADXL345sb(PinName mosi, PinName miso, PinName sck, PinName cs) : spi_(mosi, miso, sck), nCS_(cs) {
00004 
00005     nCS_ = 1;
00006     
00007     spi_.frequency(1000000);
00008     spi_.format(8,3);
00009 
00010     wait_us(500);
00011 
00012 }
00013 
00014 int ADXL345sb::adxlread(int address){
00015     int d;
00016     //address MSB must be one as it's a read
00017     address = address | 0x80;
00018     nCS_ = 0;
00019     spi_.write(address);
00020     d = spi_.write(0x00);
00021     nCS_ = 1;   
00022     return d;
00023 }
00024 void ADXL345sb::adxlmultibyteread(int address, int numOfBytes, unsigned char *buf){
00025 
00026     //address MSB must be one as it's a read
00027     address = address | 0xC0;
00028     nCS_ = 0;
00029     spi_.write(address);
00030     for(int i = 0; i < numOfBytes; i++)
00031         buf[i] = spi_.write(0x00);
00032     nCS_ = 1;   
00033 }
00034 void ADXL345sb::adxlreadXYZ(float *buf){
00035      //address MSB must be one as it's a read
00036     int address = DATAX0 | 0xC0;
00037     //set up response array and temp storeage vars
00038     unsigned char response[6];
00039     int16_t x = 0, y = 0, z = 0;    //this need to be in a 16bit int as the adxl is 10 bit res with MSB signed
00040     
00041     nCS_ = 0;
00042     spi_.write(address);
00043     for(int i = 0; i < 6; i++)
00044         response[i] = spi_.write(0x00);
00045     nCS_ = 1;
00046     
00047     x = (response[1]<<8)|response[0];
00048     y = (response[3]<<8)|response[2];
00049     z = (response[5]<<8)|response[4];
00050     
00051     buf[0] = x * 0.0078;
00052     buf[1] = y * 0.0078;
00053     buf[2] = z * 0.0078;
00054 }
00055 void ADXL345sb::adxlwrite(int address, int data){
00056     nCS_ = 0;
00057     
00058     spi_.write(address);
00059     spi_.write(data);
00060     
00061     nCS_ = 1;
00062 }