// includes outside libraries in the sketch
#include <Arduino.h>
#include <WiFi.h>
#include <WifiMulti.h>
#include <HTTPClient.h>
#include<Wire.h>

WiFiMulti WiFiMulti;

int16_t x,y,z; //Use this type, not 'int'

void setup() {
  Wire.begin(33, 32, 400000);   
  Wire.beginTransmission(0x68);
  Wire.write(0x6B); 
  Wire.write(0);    
  Wire.endTransmission(true);

  Serial.begin(115200);
  Serial.print("It's working");
  WiFiMulti.addAP("OSU_Access", "");
}
// Setup for reading the accelerometer
int16_t xArray[30]; //Use this type, not 'int'
float xavg = 0;
int16_t yArray[30];
float yavg = 0;
int16_t zArray[30];
float zavg = 0;

void loop() {
    for (int i = 0; i < 30; i++){
    Wire.beginTransmission(0x68);
    Wire.write(0x3B);  
    Wire.endTransmission(false);
    Wire.requestFrom(0x68,6,true);  
    
    x=Wire.read()<<8|Wire.read();    
    y=Wire.read()<<8|Wire.read(); 
    z=Wire.read()<<8|Wire.read(); 

    xArray[i] = x;
    yArray[i] = y;
    zArray[i] = z;

    xavg = 0;
    yavg = 0;
    zavg = 0;
    
//We used an array to find the average of the x,y, and z outputs this helps to reduce the noise
    for (int j = 0; j < 30; j++){

      xavg = xArray[j] + xavg;
      yavg = yArray[j] + yavg;
      zavg = zArray[j] + zavg;

}

    xavg = xavg / 30;
    yavg = yavg / 30;
    zavg = zavg / 30;
    }
    
 if((WiFiMulti.run() == WL_CONNECTED)) {//wait for WiFi connection
    HTTPClient http; //Creates an HTTPClient object to be used
    //Begins a request we will eventually POST
    http.begin("https://web.engr.oregonstate.edu/~patteann/My_Senor_writings.php");
    //setup thie reuest to look like an HTML form
    http.addHeader("Content-Type", "application/x-www-form-urlencoded");
    
    //Date to send with HTTP POST
    String printedValue;
    printedValue = "xavg=";
    printedValue = printedValue + xavg;
    printedValue = printedValue + "&yavg=";
    printedValue = printedValue + yavg;
    printedValue = printedValue + "&zavg=";
    printedValue = printedValue + zavg;
    Serial.print("POST data to send: ");
    Serial.println(printedValue);
  
     //Send HTTP POST request 
     int httpCode = http.POST(printedValue);
      if(httpCode > 0){//Did we get a valid response?
        if(httpCode == HTTP_CODE_OK){ // the POST happened correctly
        String payload = http.getString();
        Serial.println(payload);
        }else {
         Serial.printf("[HTTP] GET...Code: %d\n", httpCode);
         }
           }
           http.end(); //end this request
            }
            delay(5000);
 
              }
