-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsketch.ino
98 lines (79 loc) · 2.01 KB
/
sketch.ino
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <MQUnifiedsensor.h>
#define Board ("ESP-32")
#define Pin (4)
#define Threshold (23)
#define Type ("MQ-2")
#define Voltage_Resolution (3.3)
#define ADC_Bit_Resolution (12)
#define RatioMQ2CleanAir (9.83)
// MQ2 Library Instance Setup
MQUnifiedsensor MQ2(Board, Voltage_Resolution, ADC_Bit_Resolution, Pin, Type);
// Display Setup
LiquidCrystal_I2C lcd(0x27, 16, 2);
// Variables
int gas_value = 0;
void setup() {
// LCD Init
lcd.init();
lcd.begin(16, 2);
lcd.backlight();
lcd.clear();
lcd.print("Gas Sensor");
delay(1000);
// Serial Port Communication Init
Serial.begin(9600);
// Set Parameters to detect PPM concentration for LPG
MQ2.setRegressionMethod(1);
MQ2.setA(574.25);
MQ2.setB(-2.222);
// MQ2 Init
MQ2.init();
// Calibrate Sensor
Serial.print("Calibrating Sensor, please wait.");
float calcR0 = 0;
for (int i = 1; i <= 10; i++ ) {
MQ2.update();
calcR0 += MQ2.calibrate(RatioMQ2CleanAir);
Serial.print(".");
}
MQ2.setR0(calcR0/10);
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("MQ2 = ");
lcd.print(calcR0);
delay(500);
// Exception Handling
// Connection Issue Exceptions
if(isinf(calcR0)) { Serial.println("Warning: R0 value is infinite. Please check your wiring."); while(1); }
if(calcR0 == 0) { Serial.println("Warning: R0 value is zero. Please check your wiring."); while(1);}
// Show MQ2 Debug Log
MQ2.serialDebug(true);
// Threshold Pin Setup
pinMode(Threshold, INPUT);
}
void loop() {
// Update reading
MQ2.update();
MQ2.readSensor();
MQ2.serialDebug();
// Read Values
gas_value = analogRead(Pin);
gas_value = map(gas_value, 0, 4095, 0, 100);
Serial.println(gas_value);
// Show Value on Display
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("MQ2 = ");
lcd.print(gas_value);
lcd.print("%");
// Show Threshold Indicator
lcd.setCursor(0, 1);
if (digitalRead(Threshold) == HIGH) {
lcd.print("Unsafe");
} else {
lcd.print("Safe");
}
delay(500);
}