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:
- 3:ed294e830904
- Parent:
- 2:05d00b8b071d
- Child:
- 4:48545e508081
--- a/MQ2.cpp Fri Oct 06 07:38:25 2017 +0000 +++ b/MQ2.cpp Fri Oct 06 07:51:13 2017 +0000 @@ -43,8 +43,8 @@ across the load resistor and its resistance, the resistance of the sensor could be derived. ************************************************************************************/ -float MQ2::MQResistanceCalculation(int raw_adc) { - return (((float)RL_VALUE*(1023-raw_adc)/raw_adc)); +float MQ2::MQResistanceCalculation(float raw_adc) { + return (((float)RL_VALUE*(1-raw_adc)/raw_adc)); } /***************************** MQCalibration **************************************** @@ -55,14 +55,14 @@ and then divides it with RO_CLEAN_AIR_FACTOR. RO_CLEAN_AIR_FACTOR is about 10, which differs slightly between different sensors. ************************************************************************************/ -float MQ2::MQCalibration() { // This should be done in 'clean air' +float MQ2::MQCalibration() { // This should be done in 'clean air' float val=0; - for (int i=0;i<CALIBARAION_SAMPLE_TIMES;i++) { //take multiple samples - val += MQResistanceCalculation(_pin.read_u16()>>6); + for (int i=0;i<CALIBARAION_SAMPLE_TIMES;i++) { //take multiple samples + val += MQResistanceCalculation(_pin.read()); 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 + 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; } @@ -78,7 +78,7 @@ int i; float rs=0; for (i=0;i<READ_SAMPLE_TIMES;i++) { - rs += MQResistanceCalculation(_pin.read_u16()>>6); + rs += MQResistanceCalculation(_pin.read()); wait_ms(READ_SAMPLE_INTERVAL); } rs = rs/READ_SAMPLE_TIMES;