#include "LIS331DLH.h"
	

	int16_t LIS331DLH_Init(void)
	{
		uint8_t WHO;
		uint8_t nack=0;
		
		nack=I2C_transmit(LIS331DLH_ADDRESS,(uint8_t[]){LIS331DLH_REG_WHO_AM_I},1);
		nack=I2C_receive(LIS331DLH_ADDRESS,&WHO,1);
		if(WHO != 0x32)	//comunication check
			return -1;
		//27 normal mode
		nack=I2C_transmit(LIS331DLH_ADDRESS,(uint8_t[]){LIS331DLH_REG_CTRL_REG1,0x47},2);	//low power mode 0.5Hz all axis enabled
		nack=I2C_transmit(LIS331DLH_ADDRESS,(uint8_t[]){LIS331DLH_REG_CTRL_REG4,0x80},2);
		return nack;
	}	

	int16_t LIS3DH_ReadXYZ(int16_t* X, int16_t* Y, int16_t* Z)
	{
		uint8_t nack=0;
		uint8_t XYZData[8] = {0};
		nack=I2C_transmit(LIS331DLH_ADDRESS,(uint8_t[]){LIS331DLH_REG_STATUS_REG},1);	//reading status register
		delay_ms(20);
		nack=I2C_transmit(LIS331DLH_ADDRESS,(uint8_t[]){LIS331DLH_REG_OUT_X_L},1);	//reading lower half of X axis data 
		nack=I2C_receive(LIS331DLH_ADDRESS,&XYZData[0],1);
		nack=I2C_transmit(LIS331DLH_ADDRESS,(uint8_t[]){LIS331DLH_REG_OUT_X_H},1);	//reading upper half of X axis data
		nack=I2C_receive(LIS331DLH_ADDRESS,&XYZData[1],1);			
		nack=I2C_transmit(LIS331DLH_ADDRESS,(uint8_t[]){LIS331DLH_REG_OUT_Y_L},1);	//reading lower half of Y axis data
		nack=I2C_receive(LIS331DLH_ADDRESS,&XYZData[2],1);
		nack=I2C_transmit(LIS331DLH_ADDRESS,(uint8_t[]){LIS331DLH_REG_OUT_Y_H},1);	//reading upper half of Y axis data
		nack=I2C_receive(LIS331DLH_ADDRESS,&XYZData[3],1);			
		nack=I2C_transmit(LIS331DLH_ADDRESS,(uint8_t[]){LIS331DLH_REG_OUT_Z_L},1);	//reading lower half of Z axis data
		nack=I2C_receive(LIS331DLH_ADDRESS,&XYZData[4],1);
		nack=I2C_transmit(LIS331DLH_ADDRESS,(uint8_t[]){LIS331DLH_REG_OUT_Z_H},1);	//reading upper half of Z axis data
		nack=I2C_receive(LIS331DLH_ADDRESS,&XYZData[5],1);			
		*X = (int16_t)((int16_t)XYZData[0] | (int16_t)(XYZData[1]<<8));
		*Y = (int16_t)((int16_t)XYZData[2] | (int16_t)(XYZData[3]<<8));
		*Z = (int16_t)((int16_t)XYZData[4] | (int16_t)(XYZData[5]<<8));


	/*	*X = (float)(DataX*19.62f/(float)0x7FFF);
		*Y = (float)(DataY*19.62f/(float)0x7FFF);
		*Z = (float)(DataZ*19.62f/(float)0x7FFF);*/
		return nack;
	}
