#include <Wire.h> // Include Wire library for I2C communication
#include <LiquidCrystal_I2C.h> // Include LiquidCrystal_I2C library for I2C LCD
#define GAS_SENSOR_PIN A0 // Analog pin for gas sensor
#define SERVO_PIN 9 // Digital pin for servo motor
#define REGULATOR_ON HIGH // State for turning the gas regulator on
#define REGULATOR_OFF LOW // State for turning the gas regulator off
LiquidCrystal_I2C lcd(0x27, 16, 2); // Initialize the LCD with the I2C address and dimensions
Servo servo; // Create a servo object to control the servo motor
int gasValue = 0; // Variable to store gas sensor value
int threshold = 500; // Threshold value for gas detection
int regulatorState = REGULATOR_OFF; // Variable to store current state of gas regulator
void setup() {
pinMode(GAS_SENSOR_PIN, INPUT); // Set gas sensor pin as input
pinMode(SERVO_PIN, OUTPUT); // Set servo pin as output
servo.attach(SERVO_PIN); // Attach servo to its pin
servo.write(0); // Move servo to initial position (closed)
lcd.init(); // Initialize the LCD
lcd.backlight(); // Turn on LCD backlight
lcd.setCursor(0, 0);
lcd.print("Gas: ");
}
void loop() {
gasValue = analogRead(GAS_SENSOR_PIN); // Read gas sensor value
if (gasValue > threshold) {
lcd.setCursor(5, 0);
lcd.print("Leak");
// Turn off gas regulator
if (regulatorState == REGULATOR_ON) {
servo.write(0); // Close the gas regulator
regulatorState = REGULATOR_OFF;
lcd.setCursor(0, 1);
lcd.print("Regulator OFF");
}
} else {
lcd.setCursor(5, 0);
lcd.print("Safe ");
// Turn on gas regulator
if (regulatorState == REGULATOR_OFF) {
servo.write(90); // Open the gas regulator
regulatorState = REGULATOR_ON;
lcd.setCursor(0, 1);
lcd.print("Regulator ON ");
}
}
// Display gas sensor value on LCD
lcd.setCursor(5, 0);
lcd.print(" "); // Clear previous value
lcd.setCursor(5, 0);
lcd.print(gasValue);
delay(1000); // Delay for stability
}