# Carbon dioxide TGS 4161 analog sensor code

Hello everybody, I've got some problem regarding tgs 4161 analog sensor output value either it is an analog raw value or already converted voltage value itself ( volt or milivolt) Coz, I found on the github website, this person doesn't do any ADC convertion at all.

I already got the graph function from the data sheet. With 5 gain from TLC 271 op amp. The output is 380 ppm in normal concentration with 380m V selection sensitivity. BTW I'll post my code later on.

I really appreciate if you guys share the code too...

Thanks

Nice man, I am going to buy this sensor.

I need the code too.

http://www.diotronic.com/docs/tgs4161.pdf

@Star-X c

hey, here is my code..for now

CO2_cal = 0.38; //varied from 0.22 - 0.49
float ppm_last;

void GetCO2()
{
for (int i = 0; i < 4; i++)
{
delay(20);
}
CO2val = (CO2_cal)*(1024/5);
CO2val = (CO2val - senCO2) * (5/1024)*1000;
CO2ppm = pow(10, ((CO2val + 158.631)/62.877));
CO2ppm = (0.95 * ppm_last + (1 - 0.95) * CO2ppm);
ppm_last = CO2ppm;
delay(30);
}

make all math float
do not know if the math is right but there was at least a code failure! see <<<<<

``````CO2_cal = 0.38;  //varied from 0.22 - 0.49
float ppm_last;

void GetCO2()
{
for (int i = 0; i < 4; i++)
{
delay(20);
}
CO2val = (CO2_cal)*(1024.0/5.0);
CO2val = (CO2val - senCO2) * (5.0/1024.0)*1000.0;  //  5/1024 returns always  0 !!! due to integer math <<<<<<<<<<<<
CO2ppm = pow(10, ((CO2val + 158.631)/62.877));
CO2ppm = (0.95 * ppm_last + (1.0 - 0.95) * CO2ppm);
ppm_last = CO2ppm;
delay(30);
}
``````

Hello, probably it is not actual now, but it could help someone else in future...

Your code seems complicated, here is simpler version....

float EMV = 380; //varied from 220 - 490mV
float dEMV;
int CO2ppm;

void setup() {
Serial.begin(9600);
}

void loop() {

dEMV = EMV - analogRead(A0)* 5.0/1023*1000; // calculate delta EMF from ADC and EMV base
CO2ppm = exp((dEMV - b)/a); // calculate ppm (calibration constant a,b calculated from calibration or datasheet)
Serial.println(CO2ppm);
delay(1000);
}

but there are some problems...

1. Arduino has only 10bits ADC which is not enough. If You see the datasheet, dEMF changes in mV (2650ppm is proportional to 44-72mV). OAmp could amplifi, but resolution is still not enough...
2. sensor needs calibration, each have other EMF base, other slope of dEMF curve and measured value of EMF depends on ambient temperature, too. If you need accurate value, the calibration is necessary!!!
3. signal for ADC have a noise with peaks and these distort the ADC value. You could sample signal more times in time and get average value...

please be patient with my English...

cheers!
Richard