#include<Wire.h>
#include <WiFi.h>
#include <WiFiMulti.h>
#include <HTTPClient.h>

WiFiMulti wifiMulti;
int16_t x, y, z; 
float xavg, yavg, zavg;
String MACaddress;

void setup() {

  Wire.begin(33, 32, 400000);
  Wire.beginTransmission(0x68);
  Wire.write(0x6B);
  Wire.write(0);
  Wire.endTransmission(true);
  Serial.begin(115200);

  MACaddress = WiFi.macAddress(); //Get MAC address
  wifiMulti.addAP("OSU_Access", ""); //Connect to wifi


}

int16_t xArray[100];//Creates an array for each measurement with 100 measurements in it
int16_t yArray[100];
int16_t zArray[100];

void loop() {

  for (int i = 0; i < 100; 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(); //Receives measurements from accelerometer

    xArray[i] = (x) * 180.0 / (32000); //Converts measurement into an angle for each axis and stores it in the array
    yArray[i] = (y) * 180.0 / (32000);
    zArray[i] = (z) * 180.0 / (32000);
    xavg = 0;
    yavg = 0;
    zavg = 0;

    for (int j = 0; j < 100; j++) {
      xavg = xArray[j] + xavg; //Sums 100 measurements of each axis
      yavg = yArray[j] + yavg;
      zavg = zArray[j] + zavg;

    }

  }
  xavg = xavg / 100; //Divides sum by the number of elements in the array to find the average
  yavg = yavg / 100;
  zavg = zavg / 100;
  
  int k = 0;
  if (wifiMulti.run() == WL_CONNECTED) { //Make sure board connects to wifi
    HTTPClient http;
    Serial.print("[HTTP] begin...\n");
    http.begin("https://web.engr.oregonstate.edu/~wrighesc/engr103/final_in.php?x=" + String(xavg) + "&y=" + String(yavg) + "&z=" + String(zavg) + "&mac=" + MACaddress);
    //Start connection with website
    
    if (k = 200) { //Creates counter to write to website every 2 seconds
      k = 0;
      Serial.print("[HTTP] GET...\n");
      // start connection and send HTTP header
      int httpCode = http.GET();
      if (httpCode > 0) {
        // HTTP header has been send and Server response header has been handled
        Serial.printf("[HTTP] GET... code: %d\n", httpCode);
        // file found at server
        if (httpCode == HTTP_CODE_OK) {
          String payload = http.getString();
          Serial.println(payload);
        }
      } else {
        Serial.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
      }

    } else {
      k++; 
    }
  }

    delay(10);
  }
