#define BLYNK_TEMPLATE_ID           "TMPLyQLWaPXP"
#define BLYNK_DEVICE_NAME           "Quickstart Device"
#define BLYNK_AUTH_TOKEN            "BOb_Euew3kD5cMZrJq_4d7dyVVGbu2Dr"

#define BLYNK_PRINT Serial

#include <WiFi.h>
#include <WiFiClient.h>
#include <BlynkSimpleEsp32.h>
#include <LiquidCrystal_I2C.h>
#include <Adafruit_MPU6050.h>
#include <Adafruit_Sensor.h>
#include <Wire.h>
#define minval -0.05
#define maxval 0.05
#define BUZZER 13
#define LED 12

Adafruit_MPU6050 mpu;

LiquidCrystal_I2C lcd(0x27, 16, 2);  

char auth[] = BLYNK_AUTH_TOKEN;

char ssid[] = "Wokwi-GUEST";
char pass[] = "";

bool eventTrigger = false;

BlynkTimer timer;

BLYNK_CONNECTED()
{
  Blynk.setProperty(V3, "offImageUrl", "https://static-image.nyc3.cdn.digitaloceanspaces.com/general/fte/congratulations.png");
  Blynk.setProperty(V3, "onImageUrl",  "https://static-image.nyc3.cdn.digitaloceanspaces.com/general/fte/congratulations_pressed.png");
  Blynk.setProperty(V3, "url", "https://docs.blynk.io/en/getting-started/what-do-i-need-to-blynk/how-quickstart-device-was-made");
}

void myTimerEvent()
{
  sensors_event_t a, g, temp;
  mpu.getEvent(&a, &g, &temp);
if(a.acceleration.x > maxval || a.acceleration.x < minval || a.acceleration.y > maxval || a.acceleration.y < minval) {
    eventTrigger = true;
    Blynk.logEvent("gempa", "GEMPA BUMI !!");
  }
  else {
    eventTrigger = false;
  }
}



void setup(void) {
  lcd.init();               
  lcd.backlight();
  Serial.begin(115200);
  Blynk.begin(auth, ssid, pass);
  timer.setInterval(1000L, myTimerEvent);
  pinMode(BUZZER, OUTPUT);
  pinMode(LED, OUTPUT);
  lcd.print("Peringatan Dini ");
  lcd.setCursor(0, 1);
  lcd.print("   Gempa Bumi   ");
  delay (3000);
  lcd.clear();
  
  while (!Serial)
    delay(10);

  if (!mpu.begin()) {
   Serial.println("Tidak terhubung dengan sensor");
    while (1) {
      delay(10);
    }
  }

  mpu.setAccelerometerRange(MPU6050_RANGE_8_G);
  mpu.setGyroRange(MPU6050_RANGE_2000_DEG);
  mpu.setFilterBandwidth(MPU6050_BAND_21_HZ);
  delay(100);
}

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

  Blynk.run();
  timer.run();

  if(a.acceleration.x > maxval || a.acceleration.x < minval || a.acceleration.y > maxval || a.acceleration.y < minval) {
    tone(BUZZER, 800); 
    digitalWrite(LED, HIGH);
    delay(300);
    lcd.clear();
    lcd.print("***Gempa Bumi***");
    delay (1000);
    lcd.clear();
    Serial.print("X : ");
    Serial.print(a.acceleration.x);
    Serial.print(" | Y : ");
    Serial.println(a.acceleration.y);
  } else {
    noTone(BUZZER); 
    digitalWrite(LED, LOW);
    lcd.print("  Kondisi Aman  ");
    lcd.setCursor(0, 1);
    lcd.print("     Bosku     ");
  }
}