#include <looptime.h>

#define VRS 01

#define NRSUM 150
#define LOOPTIME 20

void setup()
{
  Serial.begin(9600);
  Serial.print("Acc calibg vrs: ");
  Serial.println(VRS);
}

int x1,x0,x_1, 
y1,y0,y_1, 
z1, z0, z_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()
{
  mea();
  sort();
  dmp();
  while(1);
}




