
#include <looptime.h>
/* calib of mma7361L
 AAU cansatshield v3.2
 Pin8 on acc shall be connected to D8 for switching sensitivity
 */
#define VRS 01

#define NRSUM 150
#define LOOPTIME 20

void setup()
{
  Serial.begin(9600);
  pinMode(8,OUTPUT);
  digitalWrite(8,LOW);
  Serial.print("Acc calibg vrs 1.5g and 6g version: ");
  Serial.println(VRS);
}

int 
x1,x0,x_1, 
y1,y0,y_1, 
z1, z0, z_1,
x11,x10,x1_1, 
y11,y10,y1_1, 
z11, z10, z1_1; 

long xmean, ymean, zmean;

void mm()
{
  int c;
  looptime(0);
  xmean=ymean=zmean = 0; // reset
  for (c = 0 ; c < NRSUM ; c++) {
    xmean += analogRead(2);
    ymean += analogRead(3);
    zmean += analogRead(1);
    looptime(LOOPTIME);
  }
  xmean /=NRSUM;
  ymean /=NRSUM;
  zmean /=NRSUM;
}

void st()
{
  int c;
  while (0 < Serial.available()) 
    c = Serial.read(); // empty buffer
  Serial.println("press a key for start");
  while (0 == Serial.available() ) ;
  Serial.println("..");
  delay(3000);
}

void mea()
{
  Serial.println("Calib 1 - arduino on feets...");
  // x0, y0 z1
  st();
  mm();
  x0 = xmean; 
  y0 = ymean; 
  z1 = zmean;

  Serial.println("Calib 2 -upside down");
  // x0, y0, z_1
  st();
  mm();
  z_1 = zmean;

  Serial.println("Calib 3 - stand on battery end");
  // x1 y0 z0
  st();
  mm();
  x1 = xmean; 
  z0 = zmean;

  Serial.println("Calib 4 - stand on opposite end");
  // x_1 y0 z0

  st();
  mm();
  x_1 = xmean;


  Serial.println("Calib 5 -  on radio side");
  // x0 y1 z0
  st();
  mm();
  y_1 = ymean;
  Serial.println("Calib 6 -  on analog side");
  // x0 y_1 z0
  st();
  mm();
  y1 = ymean;
}


void sort()
{
  int tmp;
  if (x1 < x_1) {
    tmp = x1;
    x1 = x_1;
    x_1 = tmp;
  }
  if (y1 < y_1) {
    tmp = y1;
    y1 = y_1;
    y_1 = tmp;
  }
  if (z1 < z_1) {
    tmp = z1;
    z1 = z_1;
    z_1 = tmp;
  }
}


void dmp()
{
  Serial.println("-----------------------");
  Serial.print("x: ");
  Serial.print(x_1); 
  Serial.print(" "); 
  Serial.print(x0);
  Serial.print(" "); 
  Serial.println(x1);

  Serial.print("y: ");
  Serial.print(y_1); 
  Serial.print(" "); 
  Serial.print(y0);
  Serial.print(" "); 
  Serial.println(y1);
  Serial.print("z: ");
  Serial.print(z_1); 
  Serial.print(" "); 
  Serial.print(z0);
  Serial.print(" "); 
  Serial.println(z1);
}

void loop()
{
  int c;
  mea();
  sort();
  dmp();
  x1_1 = x_1; 
  x10 = x0; 
  x11 = x1;
  y1_1 = y_1; 
  y10 = y0; 
  y11 = y1;
  z1_1 = z_1; 
  z10 = z0; 
  z11 = z1;
  while (0 < Serial.available()) 
    c = Serial.read(); // empty buffer
  digitalWrite(8,HIGH);
  Serial.print(" press key for 6g measurements");
  while (0 == Serial.available() ) ;
  mea();
  sort();
  Serial.println("6g results");
  dmp();
  Serial.println("1.5 g results");
  x_1 = x1_1; 
  x0 = x10; 
  x1 = x11;  
  y_1 = y1_1; 
  y0 = y10; 
  y1 = y11;  
  z_1 = z1_1; 
  z0 = z10; 
  z1 = z11;
  dmp();  
  while(1);
}








