A library for the MQ2 sensor. Based on https://github.com/labay11 and http://sandboxelectronics.com/?p=165
Dependents: mq2_example mq2_midtermproject ECE595_Group9_FinalProject mq2_example ... more
Diff: MQ2.cpp
- Revision:
- 0:a5033edf6975
- Child:
- 2:05d00b8b071d
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/MQ2.cpp Thu Oct 05 11:33:31 2017 +0000 @@ -0,0 +1,80 @@ +#include "MQ2.h" + +void MQ2::begin(){ + Ro = MQCalibration(); +} + +/* + * Reads data from MQ2. + * + * Param data: the pointer to fill. + */ +void MQ2::read(MQ2_data_t *data){ + data->lpg = MQGetGasPercentage(MQRead()/Ro,GAS_LPG); + data->co = MQGetGasPercentage(MQRead()/Ro,GAS_CO); + data->smoke = MQGetGasPercentage(MQRead()/Ro,GAS_SMOKE); +} + +/* + * reads data, returns LPG value in ppm + */ +float MQ2::readLPG(){ + return MQGetGasPercentage(MQRead()/10,GAS_LPG); +} + +/* + * reads data, returns CO value in ppm + */ +float MQ2::readCO(){ + return MQGetGasPercentage(MQRead()/10,GAS_CO); +} + +/* + * reads data, returns Smoke value in ppm + */ +float MQ2::readSmoke(){ + return MQGetGasPercentage(MQRead()/10,GAS_SMOKE); +} + +float MQ2::MQResistanceCalculation(int raw_adc) { + return (((float)RL_VALUE*(1023-raw_adc)/raw_adc)); +} + +float MQ2::MQCalibration() { + float val=0; + for (int i=0;i<CALIBARAION_SAMPLE_TIMES;i++) { //take multiple samples + val += MQResistanceCalculation(_pin.read_u16()>>6); + wait_ms(CALIBRATION_SAMPLE_INTERVAL); + } + val = val/CALIBARAION_SAMPLE_TIMES; //calculate the average value + val = val/RO_CLEAN_AIR_FACTOR; //divided by RO_CLEAN_AIR_FACTOR yields the Ro //according to the chart in the datasheet + return val; +} + +/* + * Sample the MQ2 + */ +float MQ2::MQRead() { + int i; + float rs=0; + int val = _pin.read_u16()>>6; + for (i=0;i<READ_SAMPLE_TIMES;i++) { + rs += MQResistanceCalculation(val); + wait_ms(READ_SAMPLE_INTERVAL); + } + rs = rs/READ_SAMPLE_TIMES; + return rs; +} + +float MQ2::MQGetGasPercentage(float rs_ro_ratio, GasType gas_id) { + switch(gas_id) { + case GAS_LPG: return MQGetPercentage(rs_ro_ratio,LPGCurve); + case GAS_CO: return MQGetPercentage(rs_ro_ratio,COCurve); + case GAS_SMOKE: return MQGetPercentage(rs_ro_ratio,SmokeCurve); + default: return -1.0; + } +} + +int MQ2::MQGetPercentage(float rs_ro_ratio, float *pcurve) { + return (pow(10,(((log(rs_ro_ratio)-pcurve[1])/pcurve[2]) + pcurve[0]))); +} \ No newline at end of file