#define BLYNK_PRINT Serial // Comment this out to disable prints and save space
#include <SPI.h>
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h> // <BlynkSimpleEsp8266.h>
#include <DHT.h>
#include <MQUnifiedsensor.h>

char auth[] = ""; //Enter the Auth code which was send by Blink

char ssid[] = "";
char pass[] = "";

#define DHTPIN 2 // Digital pin 4
#define DHTTYPE DHT11
#define Board ("ESP8266")
#define MQPIN (A0)
#define MQTYPE ("MQ-135")
#define Voltage_Resolution (3.33) // R1 = 1K, R2 = 2K
#define ADC_Bit_Resolution (10)
#define RatioMQ135CleanAir (3.6)

DHT dht(DHTPIN, DHTTYPE);
MQUnifiedsensor MQ135(Board, Voltage_Resolution, ADC_Bit_Resolution, MQPIN, MQTYPE);
SimpleTimer timer;

//int relay_pin = D8; // GPIO15

void sendSensor()
{
float h = dht.readHumidity();
float t = dht.readTemperature(); // or dht.readTemperature(true) for Fahrenheit
MQ135.update();
MQ135.setA(110.47); MQ135.setB(-3.18);
float co2 = MQ135.readSensor();

if (isnan(h) || isnan(t)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
// You can send any value at any time.
// Please don't send more that 10 values per second.
// MQ135.serialDebug();
Blynk.virtualWrite(V1, co2 + 400);
if (co2 > 700){
//digitalWrite(relay_pin,HIGH);
Blynk.notify("Your Snapmaker is burning.");
}
Blynk.virtualWrite(V2, h);
Blynk.virtualWrite(V3, t);
}

void setup()
{
Serial.begin(9600); // See the connection status in Serial Monitor
Blynk.begin(auth, ssid, pass);

dht.begin();
MQ135.setRegressionMethod(1);
MQ135.init();
MQ135.setRL(1);
MQ135.serialDebug(true);
// Start of calibration
Serial.print("Calibrating please wait.");
float calcR0 = 0;
for(int i = 1; i<=10; i ++)
{
MQ135.update(); // Update data, the arduino will be read the voltage on the analog pin
calcR0 += MQ135.calibrate(RatioMQ135CleanAir);
Serial.print(".");
}
MQ135.setR0(calcR0/10);
Serial.println(" done!.");

if(isinf(calcR0)) {Serial.println("Warning: Conection issue founded, R0 is infite (Open circuit detected) please check your wiring and supply"); while(1);}
if(calcR0 == 0){Serial.println("Warning: Conection issue founded, R0 is zero (Analog pin with short circuit to ground) please check your wiring and supply"); while(1);}
// End of calibration

// Setup a function to be called every second
timer.setInterval(1000L, sendSensor);
}

void loop()
{
Blynk.run(); // Initiates Blynk
timer.run(); // Initiates SimpleTimer
}