/* Here is an example program for the MQ2 CO Sensor Module that measures the CO concentration in ppm continuously and displays it on an I2C LCD 16x2 display. It also uses a piezo buzzer and a servo motor to sound an alarm and move the motor if the CO concentration is at or higher than 70 ppm.
This is just an example program and it may need to be modified according to your specific needs and the components you are using. Additionally, you may need to calibrate your sensor for accurate readings.*/
#include <Wire.h> // I2C Library
#include <LiquidCrystal_I2C.h> // Library for 16x2 LCD
#include <Servo.h> // Library for Servo Motor
// Initialize I2C LCD
LiquidCrystal_I2C lcd(0x27, 16, 2); // 0x27 is the I2C address of the LCD
// Initialize Servo Motor
Servo myservo; // create servo object to control a servo
// Define pins for Piezo Buzzer and MQ2 CO Sensor
int buzzerPin = 8;
int mq2Pin = A0;
void setup() {
// Start the Serial communication
Serial.begin(9600);
// Initialize the LCD
lcd.init();
lcd.backlight();
// Attach the Servo to pin 9
myservo.attach(9);
// Set the Servo to initial position (20 degrees)
myservo.write(20);
}
void loop() {
// Read the value of MQ2 CO Sensor
int mq2Value = analogRead(mq2Pin);
// Convert the analog reading to ppm (Parts Per Million)
float ppm = (mq2Value / 1024.0) * 10000;
// Print the ppm value to the Serial Monitor
Serial.print("CO Concentration: ");
Serial.print(ppm);
Serial.println(" ppm");
// Show the ppm value on the LCD
lcd.setCursor(0,0);
lcd.print("CO: ");
lcd.print(ppm);
lcd.print(" ppm ");
// Check if the ppm value is greater than or equal to 70 ppm
if(ppm >= 70) {
// Sound the Piezo Buzzer
tone(buzzerPin, 1000);
delay(500);
noTone(buzzerPin);
// Move the Servo Motor to 150 degrees
myservo.write(150);
} else {
// Set the Servo Motor to initial position (20 degrees)
myservo.write(20);
}
// Wait for 1 second before taking the next reading
delay(1000);
}