EmbeddedRelated.com

ADXL345 Driver

May 29, 20131 comment Coded in C for the Microchip PIC16

This is a device driver to interface ADXL345 accelerometer with PIC microcontroller(Compiled using CCS PICC)

#define ADXL_SDA  PIN_C4
#define ADXL_SCL  PIN_C3
#define ADXL_CS   PIN_C0

#use i2c(master, sda=ADXL_SDA, scl=ADXL_SCL)

void init_adxl345() 
{
   output_float(ADXL_SCL);
   output_float(ADXL_SDA);
   output_high(ADXL_CS);
}

BOOLEAN adxl345_ready() 
{
   int1 ack;
   i2c_start();            // If the write command is acknowledged,
   ack = i2c_write(0x3a);  // then the device is ready.
   i2c_stop();
   return !ack;
}

void write_adxl345(BYTE address, BYTE data) 
{
   while(!adxl345_ready());
   i2c_start();
   i2c_write(0x3a);
   i2c_write(address);
   i2c_write(data);
   i2c_stop();
}

BYTE read_adxl345(BYTE address) 
{
   BYTE data;

   while(!adxl345_ready());
   i2c_start();
   i2c_write(0x3a);
   i2c_write(address);
   i2c_start();
   i2c_write(0x3b);
   data=i2c_read(0);
   i2c_stop();
   return(data);
}

int16 read_adxl345_axis(BYTE address) 
{
   BYTE msb,lsb;

   while(!adxl345_ready());
   i2c_start();
   i2c_write(0x3a);
   i2c_write(address);
   i2c_start();
   i2c_write(0x3b);
   lsb=i2c_read(1);
   msb=i2c_read(0);
   i2c_stop();
   return((msb<<8)|lsb);
}