//For AKCE
//ADRESA pro èteni 0x39
//pro zápis 0x38



#include "C:\Users\Honza\Documents\pic\I2C_akcelerometr\main.h"
#define EEPROM_SDA  PIN_B0
#define EEPROM_SCL  PIN_B1
#use i2c(master, sda=EEPROM_SDA, scl=EEPROM_SCL)
#use rs232(baud=9600,parity=N,xmit=PIN_B3,rcv=PIN_B2,bits=8) //rcv TXD xmit RXD
#include <math.h>

void main()
{

   setup_adc_ports(NO_ANALOGS|VSS_VDD);
   setup_adc(ADC_CLOCK_DIV_2);
   setup_spi(SPI_SS_DISABLED);
   setup_timer_0(RTCC_INTERNAL|RTCC_DIV_1);
   setup_timer_1(T1_DISABLED);
   setup_timer_2(T2_DISABLED,0,1);
   setup_ccp1(CCP_OFF);
   setup_comparator(NC_NC_NC_NC);// This device COMP currently not supported by the PICWizard

printf("Simple Thermomether  \r\n",);

int16 data1, data2, data3;
signed int16 X, Y, Z;
float a, b;

unsigned int8 XL,XH,YL,YH,ZL,ZH;


 i2c_start();
   I2C_Write(0x38);
   I2C_write(0x2A);

   I2C_write(0x01);
 
   i2c_stop(); 


  
  while(TRUE)
 { 

data1=0;
data2=0 ;


//akcelerometr
   int1 ack;
   i2c_start();            // If the write command is acknowledged,
   ack = i2c_write(0x39);//hen the device is ready.
   i2c_stop();
  ack=!ack;
   
   
   
   i2c_stop();

   i2c_start();
   I2C_Write(0x38);
   I2C_write(0x01);
// i2c_stop();
   i2c_start();
   I2C_Write(0x39);
 XH=i2c_read(0);
   i2c_stop(); 

i2c_start();
   I2C_Write(0x38);
   I2C_write(0x02);
// i2c_stop();
   i2c_start();
   I2C_Write(0x39);
   XL=i2c_read(0);
   i2c_stop(); 
   
i2c_start();
   I2C_Write(0x38);
   I2C_write(0x03);
// i2c_stop();
   i2c_start();
   I2C_Write(0x39);
   YH=i2c_read(0);
   i2c_stop();  
   
i2c_start();
   I2C_Write(0x38);
   I2C_write(0x04);
// i2c_stop();
   i2c_start();
   I2C_Write(0x39);
   YL=i2c_read(0);
   i2c_stop();  
   
i2c_start();
   I2C_Write(0x38);
   I2C_write(0x05);
// i2c_stop();
   i2c_start();
   I2C_Write(0x39);
   ZH=i2c_read(0);
   i2c_stop();  
   
i2c_start();
   I2C_Write(0x38);
   I2C_write(0x06);
// i2c_stop();
   i2c_start();
   I2C_Write(0x39);
   ZL=i2c_read(0);
   i2c_stop();     
   
 i2c_start();
   I2C_Write(0x38);
   I2C_write(0x00);
// i2c_stop();
   i2c_start();
   I2C_Write(0x39);
   ZL=i2c_read(0);
   i2c_stop();    
   
 printf("Stav: %ud(procenta)\r\n", XL); 
   printf("Stav: %ud(procenta)\r\n", XH);
   printf("Stav: %ud(procenta)\r\n", YL);
   printf("Stav: %ud(procenta)\r\n", YH);
    printf("Stav: %ud(procenta)\r\n", ZL);
    printf("Stav: %ud(procenta)\r\n", ZH);
   
   
X = (((unsigned int16) XH << 8) + XL );
Y = (((unsigned int16) YH << 8) + YL);
Z = (((unsigned int16) ZH << 8) + ZL);

X=X/4;
Y=Y/4;
Z=Z/4;
//X = X>>2;
//Y = Y>>2;
//Z = Z>>2;



printf("Stav: %d (procenta)\r\n", ack);

printf("Stavx: %Ld(procenta)\r\n", X);
printf("Stavy: %Ld(procenta)\r\n", Y);
printf("Stavz: %Ld(procenta)\r\n", Z);



a=(float)Y/Z;
printf("y/z %10.2f \r\n", a);
b=atan(a);
printf("atan %10.2f \r\n", b);
b = (b/3.14)*180;
b=abs(b);
b=90-b;
printf("uhel %10.2f \r\n", b);

delay_ms (2000);

 } 
}