#include "ADXL345.h"

uint8_t ADXL_write_register (uint8_t reg_add, uint8_t data)
{
    volatile uint8_t err = 0;
    
    if(SDA_GetValue() == 0)
        I2C_recovery();
    
    err |= IICstart();
    err |= IICsend(ADXL345_ADD);
    err |= IICsend(reg_add);
    err |= IICsend(data);
    err |= IICstop();
    
    return err;
}

uint8_t ADXL_read_register (uint8_t reg_add, uint8_t *data)
{
    volatile uint8_t err = 0;
    volatile uint8_t temp;
    
    if(SDA_GetValue() == 0)
        I2C_recovery();

    err |= IICstart();
    err |= IICsend(ADXL345_ADD);
    err |= IICsend(reg_add);
    err |= IICrestart();
    err |= IICsend(ADXL345_ADD|0x01);
    temp = IICread();
    err |= IICnack();
    err |= IICstop();
    
    *data  = temp;
    return err;
}

uint8_t ADXL_init (void)
{
    uint8_t err = 0;
    //register BW_RATE
    err |= ADXL_write_register(0x2C,0x04);
    //interrupt enable (DATA_READY)
    err |= ADXL_write_register(0x2E,0x80);
    //DATA_FORMAT full resolution
    err |= ADXL_write_register(0x31,0x08);
    //POWER_CT measure
    err |= ADXL_write_register(0x2D,0x08);
    return err;
}

//citanie vystupov
uint8_t ADXL_xyz (int16_t *x, int16_t *y, int16_t *z)
{
    uint8_t err = 0;
    uint8_t i;
    uint8_t temp[6];

    if(SDA_GetValue() == 0)
        I2C_recovery();
    
    err |= IICstart();
    err |= IICsend(ADXL345_ADD);
    err |= IICsend(0x32);
    err |= IICrestart();
    err |= IICsend(ADXL345_ADD|0x01);
    for(i=0;i<6;i++)
    {
        temp[i] = IICread();
        if(i<5)
            err |= IICack();
        else
            err |= IICnack();
    }
    err |= IICstop();
    
    if(err)
        return 1;
    
    *x = (uint16_t)temp[1]<<8;
    *x |= temp[0];
    
    *y = (uint16_t)temp[3]<<8;
    *y |= temp[2];
    
    *z = (uint16_t)temp[5]<<8;
    *z |= temp[4];
    
    return 0;
}