#include <errno.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <linux/i2c-dev.h>
#include <linux/i2c.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#define i2cID 0x18
#define outXhigh 0x29
#define outYhigh 0x2B
#define outZhigh 0x2D
#define statusReg 0x27

int file;

int WriteToI2C(char arrd, char data){
	char buf[2];

	buf[0]=arrd;
	buf[1]=data;
	if (write(file, buf, 2) != 2) {
		printf("Failed to write to the i2c bus.\n");
		return -1;
	}
	return 0;
}

char ReadDataFromI2C(char arrd){
	char buf[1];
	buf[0]=arrd;
	if (write(file, buf, 1) != 1) {
		printf("Failed to write to the i2c bus.\n");
		return 0;
	}

	if(read(file, buf, 1)!=1){
		printf("Failed to read from i2c bus.\n");
		return 0;
	}

	return buf[0];
}

int main(int argc, char** argv)
{
	char filename[40];
	int i;

	char status,x_val,y_val,z_val;

	sprintf(filename,"/dev/i2c-2");

	if ((file = open(filename, O_RDWR)) < 0) {
	   printf("Failed to open the bus.");
	   /* ERROR HANDLING; you can check errno to see what went wrong */
	   exit(1);
	}

	if (ioctl(file, I2C_SLAVE, i2cID) < 0) {
	   switch (errno)
	   {
		   case ENOTTY: printf("ENOTTY error \n"); break;
		   case EINVAL: printf("EINVAL error \n"); break;
		   case EBUSY: printf("EBUSY error \n"); break;
		   default: printf("Unknown  error \n");
	   }
	   printf("Failed to acquire bus access and/or talk to slave.\n");
	   /* ERROR HANDLING; you can check errno to see what went wrong */
	   exit(1);
	}


	if(WriteToI2C(0x21,0b01000000)!=0){
		return -1;
	}

	if(WriteToI2C(0x20,0b01000111)!=0){
		return -1;
	}


   for(i=0;i<10;i++){
	   sleep(1);

	   status=ReadDataFromI2C(statusReg);
	   x_val=ReadDataFromI2C(outXhigh);
	   y_val=ReadDataFromI2C(outYhigh);
	   z_val=ReadDataFromI2C(outZhigh);

	   printf("\nstatus=%x\nx_val=%x\ny_val=%x\nz_val=%x\n",
			   status,x_val,y_val,z_val);
   }

   close(file);
   return 0;
}

