#include <WiFi.h>
#include <WiFiClient.h>
#include <Adafruit_MPU6050.h>
#include <Adafruit_Sensor.h>
#include <Wire.h>
#include "ThingSpeak.h"

WiFiClient client;

String thingSpeakAddress = "api.thingspeak.com";
String writeAPIKey;
String tsfield1Name;
String request_string;

Adafruit_MPU6050 mpu;

void setup()
{
  Serial.begin(115200);
  // Koneksi Wifi
  WiFi.disconnect();
  WiFi.begin("Wokwi-GUEST", "");
  while ((!(WiFi.status() == WL_CONNECTED))) {
    delay(300);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());

  //koneksi mpu6050
  if (!mpu.begin()) {
    Serial.println("Failed to find MPU6050 chip");
    while (1) {
      delay(10);
    }
  }
  mpu.setAccelerometerRange(MPU6050_RANGE_16_G);
  mpu.setGyroRange(MPU6050_RANGE_250_DEG);
  mpu.setFilterBandwidth(MPU6050_BAND_21_HZ);
  Serial.println("");
  delay(100);
}

//inisilisai nilai sensor
double x,y,z ;

void loop()
{
  mpu6050();
  kirim_thingspeak(x,y,z);
}

void mpu6050(){
  sensors_event_t a, g, temp;
  mpu.getEvent(&a, &g, &temp);

  x = a.acceleration.x;
  y = a.acceleration.y;
  z = a.acceleration.z;

  if ((x==0)and (y==0)){
    Serial.print("Aman : ");
    Serial.print(x);
    Serial.print(",");
    Serial.print(y);
    Serial.print(",");
    Serial.print(z);
    Serial.println(", ");
    delay(1000);

  }
  //Terjadi Gempa
  else{
    Serial.print("Gempa : ");
    Serial.print(" X: ");
    Serial.print(x);
    Serial.print(", Y: ");
    Serial.print(y);
    Serial.print(", Z: ");
    Serial.print(z);
    Serial.println(" m/s^2");
  }
  
}

void kirim_thingspeak(double x, double y,double z) {
  if (client.connect("api.thingspeak.com", 80)) {
    request_string = "/update?";
    request_string += "key=";
    request_string += "S9ZHNDWX89IG2PXU";
    request_string += "&";
    request_string += "field1";
    request_string += "=";
    request_string += x;
    request_string += "&";
    request_string += "field2";
    request_string += "=";
    request_string += y;
    request_string += "&";
    request_string += "field3";
    request_string += "=";
    request_string += z;
    }
    while (client.available()) {
      String line = client.readStringUntil('\r');
      Serial.print(line);
    }
}