const int sensorPin = A0; // The value of the load resistor (RL) // on the back of the sensor module, // in kOhm (usually between 1k and 20k) const float RL = 10.0; // Rs/Ro in clean air: from the // curve in the MQ-5 datasheet (the // MQUnifiedsensor library uses 6.5 too) const float CLEAN_AIR_RATIO = 6.5; // The LPG curve in the MQ-5 datasheet: // ppm = CURVE_A * (Rs/Ro) ^ CURVE_B // (the numbers are the MQUnifiedsensor // library's fit to that curve) const float CURVE_A = 80.897; const float CURVE_B = -2.431; // Ro: by the datasheet, the sensor's // resistance in 1000 ppm of H2, in kOhm. // Measured in clean air at start-up: // Ro = Rs in clean air / CLEAN_AIR_RATIO float Ro = 0; void setup() { Serial.begin(9600); Serial.println("Sensor warming up, please wait..."); // time for the heater inside // the sensor to settle delay(10000); // Calibration: average of 10 readings // while the sensor is in clean air Serial.println("Calibrating in clean air..."); float total = 0; int readings = 0; for (int i = 0; i < 10; i++) { float voltage = analogRead(sensorPin) * (5.0 / 1023.0); if (voltage > 0) { total += RL * (5.0 - voltage) / voltage; readings++; } delay(500); } if (readings > 0) { Ro = (total / readings) / CLEAN_AIR_RATIO; } Serial.print("Ro = "); Serial.print(Ro, 2); Serial.println(" kOhm"); } void loop() { int adc_value = analogRead(sensorPin); // Step 1: turn the 0-1023 ADC // reading into a 0-5V voltage float voltage = adc_value * (5.0 / 1023.0); // No dividing by zero: the // sensor cannot be read, // or calibration failed if (voltage == 0 || Ro == 0) { Serial.println("No data from the sensor, or a bad connection."); delay(2000); return; } // Step 2: work out the sensor's // present resistance (Rs) with: // Rs = RL * (5V - Voltage) / Voltage float Rs = RL * (5.0 - voltage) / voltage; // Step 3: find the Rs / Ro ratio (about // 6.5 in clean air, lower as gas rises) float ratio = Rs / Ro; // Step 4: PPM from the datasheet curve: // ppm = CURVE_A * (Rs/Ro) ^ CURVE_B float ppm = CURVE_A * pow(ratio, CURVE_B); // Print the result Serial.print("Raw ADC: "); Serial.print(adc_value); Serial.print(" | Voltage: "); Serial.print(voltage, 2); Serial.print("V | Rs/Ro ratio: "); Serial.print(ratio, 2); Serial.print(" | Estimated PPM: "); Serial.println(ppm, 2); // one reading every 2 seconds delay(2000); }