//create variables for x y and z data const int xAxis = A0; const int yAxis = A1; const int zAxis = A2; const int button = 2; const int readings = 10;//take multiple readings to reduce noise //initial values for acceleration double xAccel = 0.0; double yAccel = 0.0; double zAccel = 0.0; //set min and max values for x y and z int xRaw_min = 512; int xRaw_max = 512; int yRaw_min = 512; int yRaw_max = 512; int zRaw_min = 512; int zRaw_max = 512; const int sampleSize = 10; void setup() { Spark.variable("xAccel",&xAccel, DOUBLE);//create spark variables for x, y, and z coordinates Spark.variable("yAccel",&yAccel, DOUBLE); Spark.variable("zAccel",&zAccel, DOUBLE); pinMode(button, INPUT); Serial.begin(9600);//begin serial monitor } void loop() { //call function to give x y and z axis data int xRaw = readAxis(xAxis); int yRaw = readAxis(yAxis); int zRaw = readAxis(zAxis); // xAccel = xRaw; if (digitalRead(button) == LOW) { autoCalibrate(xRaw, yRaw, zRaw); } else { //convert raw values to "milli-Gs" long xScaled = map(xRaw, xRaw_min, xRaw_max, -1000, 1000); long yScaled = map(yRaw, yRaw_min, yRaw_max, -1000, 1000); long zScaled = map(zRaw, zRaw_min, zRaw_max, -1000, 1000); //rescale to fractional G xAccel = xScaled / 1000.0000; yAccel = yScaled / 1000.0000; zAccel = zScaled / 1000.0000; } delay(100); } //-------------------------------------------------------------------------------------------------------------------------------------------- //this function reads data and averages it over packages of samples int readAxis(int axisPin) { long reading = 0; //initial for reading analogRead(axisPin); //analog read axisPin delay(1); //delay for 1 mS for (int i = 0; i < sampleSize; i++) //starting at zero and for each reading until predetermined sample size { reading += analogRead(axisPin); } return reading/sampleSize; } //-------------------------------------------------------------------------------------------------------------------------------------------- //this function calibrates the accelerometer void autoCalibrate(int xRaw, int yRaw, int zRaw) { if (xRaw < xRaw_min) { xRaw_min = xRaw; } if (xRaw > xRaw_max) { xRaw_max = xRaw; } if (yRaw < yRaw_min) { yRaw_min = yRaw; } if (yRaw > yRaw_max) { yRaw_max = yRaw; } if (zRaw < zRaw_min) { zRaw_min = zRaw; } if (zRaw > zRaw_max) { zRaw_max = zRaw; } }