This circuit is designed to monitor gas levels using an MQ-2 sensor and provide a visual indication of the gas concentration through the brightness of an LED. The circuit utilizes an Arduino UNO microcontroller to read the analog output from the MQ-2 sensor, process the data, and control the LED brightness accordingly. Additionally, the circuit includes an ESP32 microcontroller connected to an LCD I2C display for potential data display purposes.
/*
MQ-2 Sensor Reading with LED Indicator
This sketch reads analog data from an MQ-2 gas sensor connected to pin A0.
It maps the sensor's 10-bit analog output to an 8-bit range and uses this
value to control the brightness of an LED connected to pin D6 using PWM.
The LED's brightness is directly proportional to the sensor's reading.
The serial monitor outputs the sensor's analog value every 500 milliseconds.
*/
// Sensor pins: D6 for LED output, A0 for analog input from MQ-2 sensor
#define ledPin 6
#define sensorPin A0
void setup() {
Serial.begin(9600); // Initialize serial communication at 9600 baud rate
pinMode(ledPin, OUTPUT); // Set the LED pin as an output
digitalWrite(ledPin, LOW); // Ensure the LED is off when starting
}
void loop() {
int sensorValue = readSensor(); // Read the sensor value
Serial.print("Analog output: "); // Print a message to the serial monitor
Serial.println(sensorValue); // Print the sensor value to the serial monitor
delay(500); // Wait for half a second before reading the sensor again
}
// This function reads the analog value from the sensor and maps it to a range suitable for PWM
int readSensor() {
unsigned int sensorValue = analogRead(sensorPin); // Read the analog value from sensor
unsigned int outputValue = map(sensorValue, 0, 1023, 0, 255); // Map the 10-bit data to 8-bit data
// Use the mapped value to set the brightness of the LED
analogWrite(ledPin, outputValue);
return sensorValue; // Return the original analog value
}
This code is designed to be uploaded to the Arduino UNO microcontroller. It reads the analog output from the MQ-2 sensor, maps the value to an 8-bit range, and adjusts the LED brightness accordingly. The sensor value is also printed to the serial monitor every 500 milliseconds.