#define BLYNK_TEMPLATE_ID "TMPL6QhPdO-v-"   // ID Template Blynk Anda
#define BLYNK_TEMPLATE_NAME "Quickstart Template"
#define BLYNK_AUTH_TOKEN "E_dmSUMUmBNPE9eDcBctkr7mlSqcO52b"

#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <MQUnifiedsensor.h>
#include <WiFi.h>
#include <BlynkSimpleEsp32.h>  // Pustaka Blynk untuk ESP32

/************************Hardware Related Macros************************************/
#define         Board                   ("ESP-32")
#define         Pin                     (4)  // Analog input pin dari ESP32

/***********************Software Related Macros************************************/
#define         Type                    ("MQ-2") // Tipe sensor
#define         Voltage_Resolution      (3.3)
#define         ADC_Bit_Resolution      (12) // Resolusi ADC ESP32
#define         RatioMQ2CleanAir        (9.83) // RS/R0 = 9.83 ppm 

/*****************************Globals***********************************************/
MQUnifiedsensor MQ2(Board, Voltage_Resolution, ADC_Bit_Resolution, Pin, Type);
LiquidCrystal_I2C lcd(0x27, 16, 2);
int valor_gas = 0;

// Informasi WiFi
char ssid[] = "Wokwi-GUEST";  // Ganti dengan SSID WiFi Anda
char pass[] = "";  // Ganti dengan password WiFi Anda

void setup() {
  Serial.begin(9600); // Inisialisasi port serial

  // Inisialisasi Blynk
  Blynk.begin(BLYNK_AUTH_TOKEN, ssid, pass);

  // Inisialisasi LCD
  lcd.begin();
  lcd.backlight();

  // Konfigurasi model matematis untuk menghitung konsentrasi PPM
  MQ2.setRegressionMethod(1); // _PPM = a * ratio^b
  MQ2.setA(574.25); MQ2.setB(-2.222); // Konfigurasi untuk LPG
  
  // Inisialisasi sensor MQ2
  MQ2.init();

  // Kalibrasi sensor
  Serial.print("Calibrating please wait.");
  float calcR0 = 0;
  for(int i = 1; i <= 10; i++) {
    MQ2.update(); // Baca data dari pin analog
    calcR0 += MQ2.calibrate(RatioMQ2CleanAir);
    Serial.print(".");
  }
  MQ2.setR0(calcR0 / 10);
  Serial.println(calcR0);

  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("MQ2 = ");
  lcd.print(calcR0);
  delay(500); // Frekuensi sampling
  
  if(isinf(calcR0)) {
    Serial.println("Warning: Connection issue, R0 is infinite. Please check wiring and power.");
    while(1);
  }
  if(calcR0 == 0) {
    Serial.println("Warning: Connection issue found, R0 is zero. Please check wiring and power.");
    while(1);
  }
  
  MQ2.serialDebug(true);
}

void loop() {
  Blynk.run(); // Memastikan koneksi ke server Blynk tetap terjaga
  MQ2.update(); // Baca data dari pin analog
  MQ2.readSensor(); // Baca konsentrasi PPM
  
  // Kirim data ke Blynk Virtual Pin V0
  Blynk.virtualWrite(V0, MQ2.getPPM());
  
  // Tampilkan data di LCD
  valor_gas = analogRead(Pin);
  valor_gas = map(valor_gas, 0, 4095, 0, 100);
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("Gas: ");
  lcd.print(valor_gas);
  
  // Tampilkan data di serial monitor
  Serial.println(valor_gas);
  
  delay(500); // Frekuensi sampling
}
mq2Breakout