//IOT project:MQ2 senor simulation on ESP32
//Member name: Jayson Tham, Afif,Isaac Xin
//Libraries and Definitions
//Includes necessary libraries for WiFi, LCD display, and MQTT.
#include <WiFi.h>
#include <LiquidCrystal_I2C.h>
#include <WiFiClient.h>
#include <PubSubClient.h>
// Defines sensor pin, buzzer pin, ADC reference voltage, ADC resolution, and LED pin.
#define sensor 34 // Analog pin where the potentiometer is connected
#define BUZZER_PIN 2 // Pin number where the buzzer is connected
#define RED_LED_PIN 23 // Pin number where the red LED is connected
#define Green_Led_PIN 19
#define Yellow_Led_PIN 18
#define ADC_REF 3.3 // ADC reference voltage
#define ADC_RESOLUTION 4095 // ADC resolution for ESP32
// Declares various variables including adc_value and Red_Led_state.
//int adc_value;
float ppm;
char Red_Led_state = LOW;
char Green_Led_state = LOW;
char Yellow_Led_state = LOW;
long previous_millis = 0;
int interval = 1000;
// Sets WiFi credentials and MQTT broker details.
const char* ssid = "Wokwi-GUEST"; // SSID and password for connecting to the WiFi.
const char* password = "";
const char* hostname = "broker.hivemq.com";
// Initializes the LCD display with I2C address 0x27 and 16x2 dimensions.
LiquidCrystal_I2C lcd(0x27, 16, 2);
WiFiClient espClient;
PubSubClient client(espClient);
const char* espClientName = "esp32Client_4770080G"; // Unique client ID for MQTT broker
int PORTNUM = 1883;
// Connects the ESP32 to the specified WiFi network.
// It keeps retrying until it gets connected, then prints the assigned IP address.
void setup_wifi()
{
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(1000);
Serial.print(".");
}
Serial.println();
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
}
// Attempts to connect to the MQTT broker. It keeps retrying until it gets connected.
void connectMQTT()
{
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
if (client.connect("esp32Client_4770080G"))
{
Serial.println("connected");
MQTTSubscribe();
}
else
{
Serial.print("Failed with state ");
Serial.print(client.state());
delay(2000);
}
}
}
void callback(String topic, byte* payload, unsigned int length)
{
String messageTemp;
Serial.print("Message received in topic: ");
Serial.print(topic);
Serial.print(" length is: ");
Serial.println(length);
Serial.print("Data received from broker: ");
for (int i = 0; i<length; i++)
{
Serial.print( (char)payload[i] );
messageTemp += (char)payload[i];
}
if (topic == "IOT/group5/project")
{
Serial.print(" Gas Level == ");
if (messageTemp == "Warning")
{
digitalWrite(Yellow_Led_PIN , HIGH);
Serial.print(" Warning! ");
}
else if (messageTemp == "Gas detected")
{
digitalWrite(RED_LED_PIN, HIGH);
Serial.print(" Gas detected! ");
}
else
{
digitalWrite(Green_Led_PIN, HIGH);
Serial.print(" Safe ");
}
}
}
void MQTTSubscribe()
{
client.subscribe("IOT/group5/project");
}
// Sets the MQTT broker's server and port.
void setup_MQTT()
{
client.setServer(hostname, PORTNUM);
client.setCallback(callback);
}
// Main setup function
// Initializes serial communication, LCD display, and pins for the buzzer and LED.
// Calls WiFi and MQTT setup functions. Displays "Gas Detector" message on the LCD.
void setup()
{
Serial.begin(115200);
delay(5000);
lcd.init();
lcd.backlight();
pinMode(BUZZER_PIN, OUTPUT);
pinMode(RED_LED_PIN, OUTPUT);
pinMode(Green_Led_PIN, OUTPUT);
pinMode(Yellow_Led_PIN, OUTPUT);
setup_wifi();
setup_MQTT();
lcd.setCursor(1, 0);
lcd.print("Gas Detector");
for (int a = 0; a <= 15; a++)
{
lcd.setCursor(a, 1);
lcd.print(".");
delay(200);
}
lcd.clear();
}
// Function to convert ADC value to ppm (assuming a linear relationship for demonstration)
// You may need to adjust the calibration values based on your sensor's datasheet and environment.
float convertToPPM(int sensorValue)
{
float voltage = sensorValue * (ADC_REF / ADC_RESOLUTION);
// Assuming a linear relationship: ppm = k * voltage (you should calibrate this properly)
float ppm = voltage * 1000; // Adjust the factor based on calibration
return ppm;
}
// Function to read gas level, update the LCD, and handle MQTT communication
void GASLevel()
{
int sensorValue = analogRead(sensor);
int gasLevel = map(sensorValue, 0, 4095, 0, 100);
//adc_value = analogRead(POT_PIN); // Read the analog value from the potentiometer
//Serial.print("ADC Value: "); // Print the ADC value for debugging
//Serial.println(sensorValue);
ppm = convertToPPM(sensorValue);
//Serial.print("PPM Value:"); // Print the PPM value for debugging
//Serial.println(ppm);
lcd.clear(); // Clear the LCD
lcd.setCursor(0, 0);
lcd.print("GAS Level: ");
lcd.print(ppm);
lcd.print("ppm");
if (ppm >= 1800) //it will trigger alarm at 55%
{ // Adjust threshold as needed
digitalWrite(BUZZER_PIN, HIGH);
tone(BUZZER_PIN, 200);
lcd.setCursor(0, 1);
lcd.print("Gas detected!!!");
//Serial.println("Gas detected");
client.publish("IOT/group5/project", "Gas detected");
//Red_Led_state = HIGH;
//Green_Led_state = LOW;
//Yellow_Led_state = LOW;
}
else if ((ppm >= 900) && (ppm <= 1800)) //28% - 55% under normal
{
digitalWrite(BUZZER_PIN, LOW);
noTone(BUZZER_PIN);
lcd.setCursor(0, 1);
lcd.print("Warning ! ! ! ");
//Serial.println("Normal");
client.publish("IOT/group5/project", "Warning");
//Red_Led_state = LOW;
//Green_Led_state = LOW;
//Yellow_Led_state = HIGH;
}
else // 0% - 27% is safe and will trigger Green Led
{
digitalWrite(BUZZER_PIN, LOW);
noTone(BUZZER_PIN);
lcd.setCursor(0, 1);
lcd.print("Safe ");
//Serial.println("Safe");
client.publish("IOT/group5/project", "Safe");
//Red_Led_state = LOW;
//Green_Led_state = HIGH;
//Yellow_Led_state = LOW;
}
digitalWrite(RED_LED_PIN, Red_Led_state);
digitalWrite(Green_Led_PIN, Green_Led_state);
digitalWrite(Yellow_Led_PIN, Yellow_Led_state);
}
// Main loop
void loop()
{
if (!client.connected())
{
connectMQTT();
}
client.loop();
long currentMillis = millis();
if ( currentMillis - previous_millis >= interval)
{
previous_millis = currentMillis;
GASLevel();
}
}