├── LICENSE ├── README.md ├── arduino_sample └── arduino_sample.ino ├── library.properties └── src ├── MQ2.cpp └── MQ2.h /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | MQ-2 sensor library 2 | =================== 3 | 4 | This is a simple library to use with the MQ-2 sensor in arduino. 5 | 6 | Based on this page: Sandbox electronics 7 | 8 | The following page it's also useful if you want to know how to calibrate the sensor (it's for MQ-6 sensor but it works as the MQ-2 does): 9 | http://www.savvymicrocontrollersolutions.com/index.php?sensor=mq-6-gas-sensors 10 | 11 | Usage 12 | ====== 13 | To intall the library to use it with the Arduino IDE, download it as zip and unzip it into your 'libraries' folder and restart the Arduino IDE. 14 | 15 | To know how to use this library view the [sample](/arduino_sample/arduino_sample.ino). 16 | 17 | Examples 18 | ========= 19 | Setup: 20 |

21 |   #include <MQ2.h>
22 |   
23 |   int pin = A0;
24 |   
25 |   MQ2 mq2(pin);
26 |   
27 |   void setup(){
28 |     mq2.begin();
29 |   }
30 | 
31 | 32 | Read all data: 33 |

34 |   float* values = mq2.read(true); //true to print the values in the Serial
35 | 
36 | 37 | Read specific data: 38 |

39 |   float lpg = mq2.readLPG();
40 |   
41 |   float co = mq2.readCO();
42 |   
43 |   float smoke = mq2.readSmoke();
44 | 
45 | 46 | License 47 | ========= 48 | Copyright 2015 labay11 49 | 50 | Licensed under the Apache License, Version 2.0 (the "License"); 51 | you may not use this file except in compliance with the License. 52 | You may obtain a copy of the License at 53 | 54 | http://www.apache.org/licenses/LICENSE-2.0 55 | 56 | Unless required by applicable law or agreed to in writing, software 57 | distributed under the License is distributed on an "AS IS" BASIS, 58 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 59 | See the License for the specific language governing permissions and 60 | limitations under the License. 61 | -------------------------------------------------------------------------------- /arduino_sample/arduino_sample.ino: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | //change this with the pin that you use 4 | int pin = A0; 5 | float lpg, co, smoke; 6 | 7 | MQ2 mq2(pin); 8 | 9 | void setup(){ 10 | Serial.begin(9600); 11 | 12 | // calibrate the device 13 | mq2.begin(); 14 | } 15 | 16 | void loop(){ 17 | 18 | /* 19 | * read the values from the sensor, it returns 20 | * an array which contains 3 values. 21 | * 0 : LPG in ppm 22 | * 1 : CO in ppm 23 | * 2 : SMOKE in ppm 24 | */ 25 | float* values= mq2.read(true); //set it false if you don't want to print the values to the Serial 26 | 27 | // lpg = values[0]; 28 | lpg = mq2.readLPG(); 29 | // co = values[1]; 30 | co = mq2.readCO(); 31 | // smoke = values[2]; 32 | smoke = mq2.readSmoke(); 33 | 34 | delay(1000); 35 | } 36 | 37 | -------------------------------------------------------------------------------- /library.properties: -------------------------------------------------------------------------------- 1 | name=MQ2-sensor 2 | version=1 3 | author=Adria Labay 4 | maintainer=Adria Labay 5 | sentence=Simple library to read and interpret data from the MQ2 snesor. 6 | paragraph=Based on this page: Sandbox electronics. The following page it's also useful if you want to know how to calibrate the sensor (it's for MQ-6 sensor but it works as the MQ-2 does): http://www.savvymicrocontrollersolutions.com/index.php?sensor=mq-6-gas-sensors. 7 | category=Sensors 8 | url=https://github.com/labay11/MQ-2-sensor-library 9 | -------------------------------------------------------------------------------- /src/MQ2.cpp: -------------------------------------------------------------------------------- 1 | #include "Arduino.h" 2 | #include "MQ2.h" 3 | 4 | MQ2::MQ2(int pin) { 5 | _pin = pin; 6 | Ro = -1.0; 7 | } 8 | 9 | void MQ2::begin(){ 10 | Ro = MQCalibration(); 11 | Serial.print("Ro: "); 12 | Serial.print(Ro); 13 | Serial.println(" kohm"); 14 | } 15 | 16 | void MQ2::close(){ 17 | Ro = -1.0; 18 | values[0] = 0.0; 19 | values[1] = 0.0; 20 | values[2] = 0.0; 21 | } 22 | 23 | bool MQ2::checkCalibration() { 24 | if (Ro < 0.0) { 25 | Serial.println("Device not calibrated, call MQ2::begin before reading any value."); 26 | return false; 27 | } 28 | 29 | return true; 30 | } 31 | 32 | float* MQ2::read(bool print){ 33 | if (!checkCalibration()) return NULL; 34 | 35 | values[0] = MQGetPercentage(LPGCurve); 36 | values[1] = MQGetPercentage(COCurve); 37 | values[2] = MQGetPercentage(SmokeCurve); 38 | 39 | lastReadTime = millis(); 40 | 41 | if (print){ 42 | Serial.print(lastReadTime); 43 | Serial.print("ms - LPG:"); 44 | Serial.print(values[0], 5); 45 | Serial.print("ppm\t"); 46 | Serial.print("CO:"); 47 | Serial.print(values[1], 5); 48 | Serial.print("ppm\t"); 49 | Serial.print("SMOKE:"); 50 | Serial.print(values[2], 5); 51 | Serial.print("ppm\n"); 52 | } 53 | 54 | return values; 55 | } 56 | 57 | float MQ2::readLPG(){ 58 | if (!checkCalibration()) return 0.0; 59 | 60 | if (millis() < (lastReadTime + READ_DELAY) && values[0] > 0) 61 | return values[0]; 62 | else 63 | return (values[0] = MQGetPercentage(LPGCurve)); 64 | } 65 | 66 | float MQ2::readCO(){ 67 | if (!checkCalibration()) return 0.0; 68 | 69 | if (millis() < (lastReadTime + READ_DELAY) && values[1] > 0) 70 | return values[1]; 71 | else 72 | return (values[1] = MQGetPercentage(COCurve)); 73 | } 74 | 75 | float MQ2::readSmoke(){ 76 | if (!checkCalibration()) return 0.0; 77 | 78 | if (millis() < (lastReadTime + READ_DELAY) && values[2] > 0) 79 | return values[2]; 80 | else 81 | return (values[2] = MQGetPercentage(SmokeCurve)); 82 | } 83 | 84 | float MQ2::MQResistanceCalculation(int raw_adc) { 85 | float flt_adc = (float) raw_adc; 86 | return RL_VALUE * (1023.0 - flt_adc) / flt_adc; 87 | } 88 | 89 | float MQ2::MQCalibration() { 90 | float val = 0.0; 91 | 92 | // take multiple samples 93 | for (int i = 0; i < CALIBARAION_SAMPLE_TIMES; i++) { 94 | val += MQResistanceCalculation(analogRead(_pin)); 95 | delay(CALIBRATION_SAMPLE_INTERVAL); 96 | } 97 | 98 | //calculate the average value 99 | val = val / ((float) CALIBARAION_SAMPLE_TIMES); 100 | 101 | //divided by RO_CLEAN_AIR_FACTOR yields the Ro according to the chart in the datasheet 102 | val = val / RO_CLEAN_AIR_FACTOR; 103 | 104 | return val; 105 | } 106 | 107 | float MQ2::MQRead() { 108 | float rs = 0.0; 109 | 110 | for (int i = 0; i < READ_SAMPLE_TIMES; i++) { 111 | rs += MQResistanceCalculation(analogRead(_pin)); 112 | delay(READ_SAMPLE_INTERVAL); 113 | } 114 | 115 | return rs / ((float) READ_SAMPLE_TIMES); // return the average 116 | } 117 | 118 | float MQ2::MQGetPercentage(float *pcurve) { 119 | float rs_ro_ratio = MQRead() / Ro; 120 | return pow(10.0, ((log(rs_ro_ratio) - pcurve[1]) / pcurve[2]) + pcurve[0]); 121 | } 122 | -------------------------------------------------------------------------------- /src/MQ2.h: -------------------------------------------------------------------------------- 1 | # ifndef MQ2_h 2 | # define MQ2_h 3 | 4 | # if ARDUINO >= 100 5 | # include "Arduino.h" 6 | # else 7 | # include "WProgram.h" 8 | # endif 9 | 10 | // define the load resistance on the board, in kilo ohms 11 | # define RL_VALUE 5.0 12 | // given constant 13 | # define RO_CLEAN_AIR_FACTOR 9.83 14 | 15 | // reads 10 times the sensor every 50ms and takes the average 16 | // NOTE: it is encouraged to take more samples during the calibration 17 | # define CALIBARAION_SAMPLE_TIMES 10 18 | # define CALIBRATION_SAMPLE_INTERVAL 50 19 | 20 | // reads 5 times the sensor every 50ms and takes the average 21 | # define READ_SAMPLE_TIMES 5 22 | # define READ_SAMPLE_INTERVAL 50 23 | 24 | // 10s, time elapsed before new data can be read. 25 | # define READ_DELAY 10000 26 | 27 | class MQ2 { 28 | public: 29 | /* 30 | * Creates the sensor by giving the pin where it is attached. 31 | */ 32 | MQ2(int pin); 33 | 34 | /* 35 | * Initialises the sensor before getting any data. 36 | * This step is necessary as it needs to be calibrated based on 37 | * current air and temperature conditions. 38 | */ 39 | void begin(); 40 | 41 | /* 42 | * Stops the sensor, calibration and any read data is deleted. 43 | * 44 | * Pin information is kept, so just call `begin()` again 45 | * to read new values, no need to create a new object. 46 | */ 47 | void close(); 48 | 49 | /* 50 | * Reads the LPG, CO and smoke data from the sensor and returns and 51 | * array with the values in this order. 52 | * 53 | * The read procedure takes `READ_SAMPLE_TIMES` samples from the sensor 54 | * every `READ_SAMPLE_INTERVAL` ms and returns the average. 55 | * 56 | * NOTE: do not modify the values of the returned array in place or deallocate it, 57 | * that could have unexpected consequences. Time to PANIC. 58 | */ 59 | float* read(bool print); 60 | 61 | /* 62 | * Same as before but only return the data from the specified gas. 63 | * 64 | * If the time elapsed since the last measurement is smaller than 65 | * `READ_DELAY`, the same prior value will be returned. 66 | */ 67 | float readLPG(); 68 | float readCO(); 69 | float readSmoke(); 70 | 71 | private: 72 | int _pin; 73 | 74 | float LPGCurve[3] = {2.3, 0.21, -0.47}; 75 | float COCurve[3] = {2.3, 0.72, -0.34}; 76 | float SmokeCurve[3] = {2.3, 0.53, -0.44}; 77 | float Ro = -1.0; 78 | 79 | float values[3]; // array with the measured values in the order: lpg, CO and smoke 80 | 81 | float MQRead(); 82 | float MQGetPercentage(float *pcurve); 83 | float MQCalibration(); 84 | float MQResistanceCalculation(int raw_adc); 85 | bool checkCalibration(); 86 | 87 | int lastReadTime = 0; 88 | }; 89 | 90 | # endif 91 | --------------------------------------------------------------------------------