hi all
recently i'm building a device that monitor CO2 concentration in my room
in this device i use a MG811 module as the CO2 sensor as shown below
and i wrote some code to get the analog voltage from the sensor
the voltage displayed in LCD was very unstable
i can't find obvious change while i exhale the sensor
initially i believed it resulted from unstable output of the sensor
but when i tried using a Fluke multimeter to test
the reading on multimeter was very stable
and the voltage changed as i exhale it
i had a wrong wiring or codes?
plz help
#include <LiquidCrystal_I2C.h> //quote the library of IIC LCD
LiquidCrystal_I2C L(0x27,2,1,0,4,5,6,7,3,POSITIVE); //set the LCD address to 0x27 for a 16x2 display
void setup()
{
//Serial.begin(9600); //open communication port
pinMode(13,OUTPUT);
digitalWrite(13,LOW); //close the LED connected to pin13
//pinMode(12,OUTPUT);
//digitalWrite(12,HIGH);
L.begin(16,2); //initialize LCD as a 16x2 sheet
}
float Vin; // analog voltage from sensor
float Vex; // exponent value of Vin
float MGR(int IN)
{
pinMode(IN,INPUT);
int i;
int times=1;
float x=0;
for(i=1;i<=times;i++)
{
x=x+analogRead(IN);
delay(10);
}
x=x/times; //sum the voltage measured for ten times and divide it by ten
return x;
}
// the function that calculate the average voltage read in pin IN
// take several samples and get the average
// the interval of every sampling is 10ms
float PPM(float Vin)
{
float A=10000;
float B=5;
float x=A*pow(B,Vin);
return x;
}
// build a function that transfer input voltage to CO2 concentration
// the equation is PPM=A*B^Vin
// A and B are constant coefficients to be determined by calibration
void loop()
{
Vin=MGR(14); // get analog signal from A0 pin
Vin=Vin*5/1023; // transfer the voltage from digital value to real value
Vex=PPM(Vin); // calculate CO2 concentration
//Serial.println(Vin,3);
//Serial.print(" V ");
//Serial.print(Vex,0);
//Serial.println(" ppm");
L.setCursor(0,0);
L.print(Vin,3); //print analog signal on first row of LCD
L.setCursor(0,1);
L.print(Vex,0); //print CO2 concentration on second row of LCD
delay(1000);
}
MG811_CO2_Sensor.ino (1.63 KB)