#define CO2_SENSOR_PIN 36 // Analog pin connected to MG811 AOUT
// Calibration constants
#define ZERO_POINT_VOLTAGE 0.4 // Voltage at 400 ppm CO2
#define CO2_SCALING_FACTOR 0.02 // Voltage change per ppm (approximate)
void setup() {
Serial.begin(115200); // For debugging
analogReadResolution(12); // Set ADC resolution to 12-bit
Serial.println("MG811 CO2 Sensor Initialized");
}
void loop() {
int adcValue = analogRead(CO2_SENSOR_PIN); // Read raw ADC value
float sensorVoltage = adcValue * (3.3 / 4095.0); // Convert to voltage (3.3V ADC reference)
// Calculate CO2 concentration (ppm) using the voltage difference
float co2Concentration = calculateCO2(sensorVoltage);
// Print sensor readings
Serial.print("Sensor Voltage: ");
Serial.print(sensorVoltage);
Serial.print(" V | CO2 Concentration: ");
Serial.print(co2Concentration);
Serial.println(" ppm");
delay(2000); // Delay for stability
}
// Function to calculate CO2 concentration from voltage
float calculateCO2(float voltage) {
if (voltage < ZERO_POINT_VOLTAGE) {
return 400; // Minimum ppm (ambient level)
}
return 400 + ((voltage - ZERO_POINT_VOLTAGE) / CO2_SCALING_FACTOR);
}