//PROGRAMME CANSAT
//BY GOUENARD & BURTAIRE

 //Configuration physique
 //ADXL345
     // Digital 10  -> CS
     // Digital 11  -> SDA
     // Digital 12 -> SDO
     // Digital 13 -> SDL
 //ZIGBEE
     // Digital 6 -> RX
     // Digital 7 -> TX
 //TEMPERATURE
     // Analog 0 -> input
   

/***** ZIGBEE *****/
//Librairie pour utiliser le port serie virtuel
#include <SoftwareSerial.h>

// Software Serial RX
const int rxpin = 6;
// Software Serial TX
const int txpin = 7;                 
SoftwareSerial mySerial(rxpin, txpin);


/****** TEMPERATURE *****/
// Temperature on pin A0 
int temperaturePin = 0;
int mesure = 0;


/***** ACCELEROMETRE *****/
//Librairie pour la connexion en SPI
#include <SPI.h>

//Definition de l'adresse de l'accelerometre
#define Address 0x53

//Definition des registres de l'accelerometre
#define ADXL345_POWER_CTL 0x2D
#define ADXL345_DATA_FORMAT 0x31
#define ADXL345_DATAX0 0x32
#define ADXL345_DATAX1 0x33
#define ADXL345_DATAY0 0x34
#define ADXL345_DATAY1 0x35
#define ADXL345_DATAZ0 0x36
#define ADXL345_DATAZ1 0x37


void ecritureSPI(byte registre, byte data)
{
  digitalWrite(10,LOW);
  SPI.transfer(registre);
  SPI.transfer(data); 
  digitalWrite(10,HIGH); 
}

byte lectureSPI(byte registre)
{
  digitalWrite(10,LOW); 
  SPI.transfer(0x80 | registre);
  byte data = SPI.transfer(0xFF);
  digitalWrite(10,HIGH); 

  return data;
}

void valeurs_acc(int *x, int *y, int *z)
{
  *x =(int) ((lectureSPI(ADXL345_DATAX1)<<8)|lectureSPI(ADXL345_DATAX0))+511;
  *y =(int) ((lectureSPI(ADXL345_DATAY1)<<8)|lectureSPI(ADXL345_DATAY0))+511;
  *z =(int) ((lectureSPI(ADXL345_DATAZ1)<<8)|lectureSPI(ADXL345_DATAZ0))+511;
}


// Convertit la valeur de la tension du capteur en température
float tmp_convert(int pin) 
{
 float temperature; 
 temperature = analogRead(pin) * .004882814;
 temperature = (temperature - 0.5) * 100;
 return temperature;
}

void aff_tmp(void) {
  if(mesure==10) {
  float temperature;
  temperature = tmp_convert(temperaturePin);
  mySerial.println(temperature);
  mesure=0; 
  }
  else mesure++;
}

void aff_acc(void) {
  int x, y, z;
  valeurs_acc(&x, &y, &z); 
  
  Serial.print("X : ");
  Serial.println(x);
  Serial.print("Y : ");
  Serial.println(y);
  Serial.print("Z : ");
  Serial.println(z);
  Serial.println("");
  
  mySerial.print("X : ");
  mySerial.println(x);
  mySerial.print("Y : ");
  mySerial.println(y);
  mySerial.print("Z : ");
  mySerial.println(z);
  mySerial.println("");
}


void setup()  
{
  Serial.begin(9600);
  // Initialisation du Software Serial
  mySerial.begin(9600);
  mySerial.println("Debut du programme");

  pinMode(10,OUTPUT); //CS
  pinMode(11,OUTPUT); //SDA
  pinMode(12,INPUT); //SDO
  pinMode(13,OUTPUT); //SCL
  
  SPI.begin(); 
  SPI.setDataMode(SPI_MODE3); 
  ecritureSPI(ADXL345_DATA_FORMAT, 0x01); 
  ecritureSPI(ADXL345_POWER_CTL, 0x08);
 
 
}

void loop() 
{
  aff_acc();
  aff_tmp(); 

  delay(500);
}


