From d4fdef44d40ab2ffdcb92cb0fbb8146465e9c728 Mon Sep 17 00:00:00 2001 From: Chris Date: Sat, 8 Jul 2017 07:27:43 -0700 Subject: [PATCH 1/6] Added MQ135 Support Added support for a MQ135 gas sensor --- .../bruh_mqtt_multisensor_github.ino | 1269 +++++++++-------- 1 file changed, 640 insertions(+), 629 deletions(-) diff --git a/bruh_mqtt_multisensor_github/bruh_mqtt_multisensor_github.ino b/bruh_mqtt_multisensor_github/bruh_mqtt_multisensor_github.ino index 6615f5c..dfbf4fd 100644 --- a/bruh_mqtt_multisensor_github/bruh_mqtt_multisensor_github.ino +++ b/bruh_mqtt_multisensor_github/bruh_mqtt_multisensor_github.ino @@ -1,630 +1,641 @@ -/* - .______ .______ __ __ __ __ ___ __ __ .___________. ______ .___ ___. ___ .___________. __ ______ .__ __. - | _ \ | _ \ | | | | | | | | / \ | | | | | | / __ \ | \/ | / \ | || | / __ \ | \ | | - | |_) | | |_) | | | | | | |__| | / ^ \ | | | | `---| |----`| | | | | \ / | / ^ \ `---| |----`| | | | | | | \| | - | _ < | / | | | | | __ | / /_\ \ | | | | | | | | | | | |\/| | / /_\ \ | | | | | | | | | . ` | - | |_) | | |\ \-.| `--' | | | | | / _____ \ | `--' | | | | `--' | | | | | / _____ \ | | | | | `--' | | |\ | - |______/ | _| `.__| \______/ |__| |__| /__/ \__\ \______/ |__| \______/ |__| |__| /__/ \__\ |__| |__| \______/ |__| \__| - - Thanks much to @corbanmailloux for providing a great framework for implementing flash/fade with HomeAssistant https://github.com/corbanmailloux/esp-mqtt-rgb-led - - To use this code you will need the following dependancies: - - - Support for the ESP8266 boards. - - You can add it to the board manager by going to File -> Preference and pasting http://arduino.esp8266.com/stable/package_esp8266com_index.json into the Additional Board Managers URL field. - - Next, download the ESP8266 dependancies by going to Tools -> Board -> Board Manager and searching for ESP8266 and installing it. - - - You will also need to download the follow libraries by going to Sketch -> Include Libraries -> Manage Libraries - - DHT sensor library - - Adafruit unified sensor - - PubSubClient - - ArduinoJSON - - UPDATE 16 MAY 2017 by Knutella - Fixed MQTT disconnects when wifi drops by moving around Reconnect and adding a software reset of MCU - - UPDATE 23 MAY 2017 - The MQTT_MAX_PACKET_SIZE parameter may not be setting appropriately do to a bug in the PubSub library. If the MQTT messages are not being transmitted as expected please you may need to change the MQTT_MAX_PACKET_SIZE parameter in "PubSubClient.h" directly. - -*/ - - - -#include -#include -#include -#include -#include -#include -#include - - - -/************ WIFI and MQTT INFORMATION (CHANGE THESE FOR YOUR SETUP) ******************/ -#define wifi_ssid "YourSSID" //type your WIFI information inside the quotes -#define wifi_password "YourWIFIpassword" -#define mqtt_server "your.mqtt.server.ip" -#define mqtt_user "yourMQTTusername" -#define mqtt_password "yourMQTTpassword" -#define mqtt_port 1883 - - - -/************* MQTT TOPICS (change these topics as you wish) **************************/ -#define light_state_topic "bruh/sensornode1" -#define light_set_topic "bruh/sensornode1/set" - -const char* on_cmd = "ON"; -const char* off_cmd = "OFF"; - - - -/**************************** FOR OTA **************************************************/ -#define SENSORNAME "sensornode1" -#define OTApassword "YouPassword" // change this to whatever password you want to use when you upload OTA -int OTAport = 8266; - - - -/**************************** PIN DEFINITIONS ********************************************/ -const int redPin = D1; -const int greenPin = D2; -const int bluePin = D3; -#define PIRPIN D5 -#define DHTPIN D7 -#define DHTTYPE DHT22 -#define LDRPIN A0 - - - -/**************************** SENSOR DEFINITIONS *******************************************/ -float ldrValue; -int LDR; -float calcLDR; -float diffLDR = 25; - -float diffTEMP = 0.2; -float tempValue; - -float diffHUM = 1; -float humValue; - -int pirValue; -int pirStatus; -String motionStatus; - -char message_buff[100]; - -int calibrationTime = 0; - -const int BUFFER_SIZE = 300; - -#define MQTT_MAX_PACKET_SIZE 512 - - -/******************************** GLOBALS for fade/flash *******************************/ -byte red = 255; -byte green = 255; -byte blue = 255; -byte brightness = 255; - -byte realRed = 0; -byte realGreen = 0; -byte realBlue = 0; - -bool stateOn = false; - -bool startFade = false; -unsigned long lastLoop = 0; -int transitionTime = 0; -bool inFade = false; -int loopCount = 0; -int stepR, stepG, stepB; -int redVal, grnVal, bluVal; - -bool flash = false; -bool startFlash = false; -int flashLength = 0; -unsigned long flashStartTime = 0; -byte flashRed = red; -byte flashGreen = green; -byte flashBlue = blue; -byte flashBrightness = brightness; - - - -WiFiClient espClient; -PubSubClient client(espClient); -DHT dht(DHTPIN, DHTTYPE); - - - -/********************************** START SETUP*****************************************/ -void setup() { - - Serial.begin(115200); - - pinMode(PIRPIN, INPUT); - pinMode(DHTPIN, INPUT); - pinMode(LDRPIN, INPUT); - - Serial.begin(115200); - delay(10); - - ArduinoOTA.setPort(OTAport); - - ArduinoOTA.setHostname(SENSORNAME); - - ArduinoOTA.setPassword((const char *)OTApassword); - - Serial.print("calibrating sensor "); - for (int i = 0; i < calibrationTime; i++) { - Serial.print("."); - delay(1000); - } - - Serial.println("Starting Node named " + String(SENSORNAME)); - - - setup_wifi(); - - client.setServer(mqtt_server, mqtt_port); - client.setCallback(callback); - - - ArduinoOTA.onStart([]() { - Serial.println("Starting"); - }); - ArduinoOTA.onEnd([]() { - Serial.println("\nEnd"); - }); - ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) { - Serial.printf("Progress: %u%%\r", (progress / (total / 100))); - }); - ArduinoOTA.onError([](ota_error_t error) { - Serial.printf("Error[%u]: ", error); - if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed"); - else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed"); - else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed"); - else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed"); - else if (error == OTA_END_ERROR) Serial.println("End Failed"); - }); - ArduinoOTA.begin(); - Serial.println("Ready"); - Serial.print("IPess: "); - Serial.println(WiFi.localIP()); - reconnect(); -} - - - - -/********************************** START SETUP WIFI*****************************************/ -void setup_wifi() { - - delay(10); - Serial.println(); - Serial.print("Connecting to "); - Serial.println(wifi_ssid); - - WiFi.mode(WIFI_STA); - WiFi.begin(wifi_ssid, wifi_password); - - while (WiFi.status() != WL_CONNECTED) { - delay(500); - Serial.print("."); - } - - Serial.println(""); - Serial.println("WiFi connected"); - Serial.println("IP address: "); - Serial.println(WiFi.localIP()); -} - - - -/********************************** START CALLBACK*****************************************/ -void callback(char* topic, byte* payload, unsigned int length) { - Serial.print("Message arrived ["); - Serial.print(topic); - Serial.print("] "); - - char message[length + 1]; - for (int i = 0; i < length; i++) { - message[i] = (char)payload[i]; - } - message[length] = '\0'; - Serial.println(message); - - if (!processJson(message)) { - return; - } - - if (stateOn) { - // Update lights - realRed = map(red, 0, 255, 0, brightness); - realGreen = map(green, 0, 255, 0, brightness); - realBlue = map(blue, 0, 255, 0, brightness); - } - else { - realRed = 0; - realGreen = 0; - realBlue = 0; - } - - startFade = true; - inFade = false; // Kill the current fade - - sendState(); -} - - - -/********************************** START PROCESS JSON*****************************************/ -bool processJson(char* message) { - StaticJsonBuffer jsonBuffer; - - JsonObject& root = jsonBuffer.parseObject(message); - - if (!root.success()) { - Serial.println("parseObject() failed"); - return false; - } - - if (root.containsKey("state")) { - if (strcmp(root["state"], on_cmd) == 0) { - stateOn = true; - } - else if (strcmp(root["state"], off_cmd) == 0) { - stateOn = false; - } - } - - // If "flash" is included, treat RGB and brightness differently - if (root.containsKey("flash")) { - flashLength = (int)root["flash"] * 1000; - - if (root.containsKey("brightness")) { - flashBrightness = root["brightness"]; - } - else { - flashBrightness = brightness; - } - - if (root.containsKey("color")) { - flashRed = root["color"]["r"]; - flashGreen = root["color"]["g"]; - flashBlue = root["color"]["b"]; - } - else { - flashRed = red; - flashGreen = green; - flashBlue = blue; - } - - flashRed = map(flashRed, 0, 255, 0, flashBrightness); - flashGreen = map(flashGreen, 0, 255, 0, flashBrightness); - flashBlue = map(flashBlue, 0, 255, 0, flashBrightness); - - flash = true; - startFlash = true; - } - else { // Not flashing - flash = false; - - if (root.containsKey("color")) { - red = root["color"]["r"]; - green = root["color"]["g"]; - blue = root["color"]["b"]; - } - - if (root.containsKey("brightness")) { - brightness = root["brightness"]; - } - - if (root.containsKey("transition")) { - transitionTime = root["transition"]; - } - else { - transitionTime = 0; - } - } - - return true; -} - - - -/********************************** START SEND STATE*****************************************/ -void sendState() { - StaticJsonBuffer jsonBuffer; - - JsonObject& root = jsonBuffer.createObject(); - - root["state"] = (stateOn) ? on_cmd : off_cmd; - JsonObject& color = root.createNestedObject("color"); - color["r"] = red; - color["g"] = green; - color["b"] = blue; - - - root["brightness"] = brightness; - root["humidity"] = (String)humValue; - root["motion"] = (String)motionStatus; - root["ldr"] = (String)LDR; - root["temperature"] = (String)tempValue; - root["heatIndex"] = (String)calculateHeatIndex(humValue, tempValue); - - - char buffer[root.measureLength() + 1]; - root.printTo(buffer, sizeof(buffer)); - - Serial.println(buffer); - client.publish(light_state_topic, buffer, true); -} - - -/* - * Calculate Heat Index value AKA "Real Feel" - * NOAA heat index calculations taken from - * http://www.wpc.ncep.noaa.gov/html/heatindex_equation.shtml - */ -float calculateHeatIndex(float humidity, float temp) { - float heatIndex= 0; - if (temp >= 80) { - heatIndex = -42.379 + 2.04901523*temp + 10.14333127*humidity; - heatIndex = heatIndex - .22475541*temp*humidity - .00683783*temp*temp; - heatIndex = heatIndex - .05481717*humidity*humidity + .00122874*temp*temp*humidity; - heatIndex = heatIndex + .00085282*temp*humidity*humidity - .00000199*temp*temp*humidity*humidity; - } else { - heatIndex = 0.5 * (temp + 61.0 + ((temp - 68.0)*1.2) + (humidity * 0.094)); - } - - if (humidity < 13 && 80 <= temp <= 112) { - float adjustment = ((13-humidity)/4) * sqrt((17-abs(temp-95.))/17); - heatIndex = heatIndex - adjustment; - } - - return heatIndex; -} - - -/********************************** START SET COLOR *****************************************/ -void setColor(int inR, int inG, int inB) { - analogWrite(redPin, inR); - analogWrite(greenPin, inG); - analogWrite(bluePin, inB); - - Serial.println("Setting LEDs:"); - Serial.print("r: "); - Serial.print(inR); - Serial.print(", g: "); - Serial.print(inG); - Serial.print(", b: "); - Serial.println(inB); -} - - - -/********************************** START RECONNECT*****************************************/ -void reconnect() { - // Loop until we're reconnected - while (!client.connected()) { - Serial.print("Attempting MQTT connection..."); - // Attempt to connect - if (client.connect(SENSORNAME, mqtt_user, mqtt_password)) { - Serial.println("connected"); - client.subscribe(light_set_topic); - setColor(0, 0, 0); - sendState(); - } else { - Serial.print("failed, rc="); - Serial.print(client.state()); - Serial.println(" try again in 5 seconds"); - // Wait 5 seconds before retrying - delay(5000); - } - } -} - - - -/********************************** START CHECK SENSOR **********************************/ -bool checkBoundSensor(float newValue, float prevValue, float maxDiff) { - return newValue < prevValue - maxDiff || newValue > prevValue + maxDiff; -} - - -/********************************** START MAIN LOOP***************************************/ -void loop() { - - ArduinoOTA.handle(); - - if (!client.connected()) { - // reconnect(); - software_Reset(); - } - client.loop(); - - if (!inFade) { - - float newTempValue = dht.readTemperature(true); //to use celsius remove the true text inside the parentheses - float newHumValue = dht.readHumidity(); - - //PIR CODE - pirValue = digitalRead(PIRPIN); //read state of the - - if (pirValue == LOW && pirStatus != 1) { - motionStatus = "standby"; - sendState(); - pirStatus = 1; - } - - else if (pirValue == HIGH && pirStatus != 2) { - motionStatus = "motion detected"; - sendState(); - pirStatus = 2; - } - - delay(100); - - if (checkBoundSensor(newTempValue, tempValue, diffTEMP)) { - tempValue = newTempValue; - sendState(); - } - - if (checkBoundSensor(newHumValue, humValue, diffHUM)) { - humValue = newHumValue; - sendState(); - } - - - int newLDR = analogRead(LDRPIN); - - if (checkBoundSensor(newLDR, LDR, diffLDR)) { - LDR = newLDR; - sendState(); - } - - } - - if (flash) { - if (startFlash) { - startFlash = false; - flashStartTime = millis(); - } - - if ((millis() - flashStartTime) <= flashLength) { - if ((millis() - flashStartTime) % 1000 <= 500) { - setColor(flashRed, flashGreen, flashBlue); - } - else { - setColor(0, 0, 0); - // If you'd prefer the flashing to happen "on top of" - // the current color, uncomment the next line. - // setColor(realRed, realGreen, realBlue); - } - } - else { - flash = false; - setColor(realRed, realGreen, realBlue); - } - } - - if (startFade) { - // If we don't want to fade, skip it. - if (transitionTime == 0) { - setColor(realRed, realGreen, realBlue); - - redVal = realRed; - grnVal = realGreen; - bluVal = realBlue; - - startFade = false; - } - else { - loopCount = 0; - stepR = calculateStep(redVal, realRed); - stepG = calculateStep(grnVal, realGreen); - stepB = calculateStep(bluVal, realBlue); - - inFade = true; - } - } - - if (inFade) { - startFade = false; - unsigned long now = millis(); - if (now - lastLoop > transitionTime) { - if (loopCount <= 1020) { - lastLoop = now; - - redVal = calculateVal(stepR, redVal, loopCount); - grnVal = calculateVal(stepG, grnVal, loopCount); - bluVal = calculateVal(stepB, bluVal, loopCount); - - setColor(redVal, grnVal, bluVal); // Write current values to LED pins - - Serial.print("Loop count: "); - Serial.println(loopCount); - loopCount++; - } - else { - inFade = false; - } - } - } -} - - - - -/**************************** START TRANSITION FADER *****************************************/ -// From https://www.arduino.cc/en/Tutorial/ColorCrossfader -/* BELOW THIS LINE IS THE MATH -- YOU SHOULDN'T NEED TO CHANGE THIS FOR THE BASICS - - The program works like this: - Imagine a crossfade that moves the red LED from 0-10, - the green from 0-5, and the blue from 10 to 7, in - ten steps. - We'd want to count the 10 steps and increase or - decrease color values in evenly stepped increments. - Imagine a + indicates raising a value by 1, and a - - equals lowering it. Our 10 step fade would look like: - - 1 2 3 4 5 6 7 8 9 10 - R + + + + + + + + + + - G + + + + + - B - - - - - The red rises from 0 to 10 in ten steps, the green from - 0-5 in 5 steps, and the blue falls from 10 to 7 in three steps. - - In the real program, the color percentages are converted to - 0-255 values, and there are 1020 steps (255*4). - - To figure out how big a step there should be between one up- or - down-tick of one of the LED values, we call calculateStep(), - which calculates the absolute gap between the start and end values, - and then divides that gap by 1020 to determine the size of the step - between adjustments in the value. -*/ -int calculateStep(int prevValue, int endValue) { - int step = endValue - prevValue; // What's the overall gap? - if (step) { // If its non-zero, - step = 1020 / step; // divide by 1020 - } - - return step; -} - -/* The next function is calculateVal. When the loop value, i, - reaches the step size appropriate for one of the - colors, it increases or decreases the value of that color by 1. - (R, G, and B are each calculated separately.) -*/ -int calculateVal(int step, int val, int i) { - if ((step) && i % step == 0) { // If step is non-zero and its time to change a value, - if (step > 0) { // increment the value if step is positive... - val += 1; - } - else if (step < 0) { // ...or decrement it if step is negative - val -= 1; - } - } - - // Defensive driving: make sure val stays in the range 0-255 - if (val > 255) { - val = 255; - } - else if (val < 0) { - val = 0; - } - - return val; -} - -/****reset***/ -void software_Reset() // Restarts program from beginning but does not reset the peripherals and registers -{ -Serial.print("resetting"); -ESP.reset(); +/* + .______ .______ __ __ __ __ ___ __ __ .___________. ______ .___ ___. ___ .___________. __ ______ .__ __. + | _ \ | _ \ | | | | | | | | / \ | | | | | | / __ \ | \/ | / \ | || | / __ \ | \ | | + | |_) | | |_) | | | | | | |__| | / ^ \ | | | | `---| |----`| | | | | \ / | / ^ \ `---| |----`| | | | | | | \| | + | _ < | / | | | | | __ | / /_\ \ | | | | | | | | | | | |\/| | / /_\ \ | | | | | | | | | . ` | + | |_) | | |\ \-.| `--' | | | | | / _____ \ | `--' | | | | `--' | | | | | / _____ \ | | | | | `--' | | |\ | + |______/ | _| `.__| \______/ |__| |__| /__/ \__\ \______/ |__| \______/ |__| |__| /__/ \__\ |__| |__| \______/ |__| \__| + + Thanks much to @corbanmailloux for providing a great framework for implementing flash/fade with HomeAssistant https://github.com/corbanmailloux/esp-mqtt-rgb-led + + To use this code you will need the following dependancies: + + - Support for the ESP8266 boards. + - You can add it to the board manager by going to File -> Preference and pasting http://arduino.esp8266.com/stable/package_esp8266com_index.json into the Additional Board Managers URL field. + - Next, download the ESP8266 dependancies by going to Tools -> Board -> Board Manager and searching for ESP8266 and installing it. + + - You will also need to download the follow libraries by going to Sketch -> Include Libraries -> Manage Libraries + - DHT sensor library + - Adafruit unified sensor + - PubSubClient + - ArduinoJSON + + UPDATE 16 MAY 2017 by Knutella - Fixed MQTT disconnects when wifi drops by moving around Reconnect and adding a software reset of MCU + + UPDATE 23 MAY 2017 - The MQTT_MAX_PACKET_SIZE parameter may not be setting appropriately do to a bug in the PubSub library. If the MQTT messages are not being transmitted as expected please you may need to change the MQTT_MAX_PACKET_SIZE parameter in "PubSubClient.h" directly. + +*/ + + + +#include +#include +#include +#include +#include +#include +#include +#include + + + +/************ WIFI and MQTT INFORMATION (CHANGE THESE FOR YOUR SETUP) ******************/ +#define wifi_ssid "YourSSID" //type your WIFI information inside the quotes +#define wifi_password "YourWIFIpassword" +#define mqtt_server "your.mqtt.server.ip" +#define mqtt_user "yourMQTTusername" +#define mqtt_password "yourMQTTpassword" +#define mqtt_port 1883 + + + +/************* MQTT TOPICS (change these topics as you wish) **************************/ +#define light_state_topic "bruh/sensornode1" +#define light_set_topic "bruh/sensornode1/set" + +const char* on_cmd = "ON"; +const char* off_cmd = "OFF"; + + + +/**************************** FOR OTA **************************************************/ +#define SENSORNAME "sensornode1" +#define OTApassword "YouPassword" // change this to whatever password you want to use when you upload OTA +int OTAport = 8266; + + + +/**************************** PIN DEFINITIONS ********************************************/ +const int redPin = D1; +const int greenPin = D2; +const int bluePin = D3; +#define PIRPIN D5 +#define DHTPIN D7 +#define DHTTYPE DHT22 +#define LDRPIN A0 +#define MQ135PIN A1 // change this to the pin of the MQ135 + + + +/**************************** SENSOR DEFINITIONS *******************************************/ +float ldrValue; +int LDR; +float calcLDR; +float diffLDR = 25; + +float diffTEMP = 0.2; +float tempValue; + +float diffHUM = 1; +float humValue; + +int pirValue; +int pirStatus; +String motionStatus; + +char message_buff[100]; + +int calibrationTime = 0; + +const int BUFFER_SIZE = 300; + +#define MQTT_MAX_PACKET_SIZE 512 + + +/******************************** GLOBALS for fade/flash *******************************/ +byte red = 255; +byte green = 255; +byte blue = 255; +byte brightness = 255; + +byte realRed = 0; +byte realGreen = 0; +byte realBlue = 0; + +bool stateOn = false; + +bool startFade = false; +unsigned long lastLoop = 0; +int transitionTime = 0; +bool inFade = false; +int loopCount = 0; +int stepR, stepG, stepB; +int redVal, grnVal, bluVal; + +bool flash = false; +bool startFlash = false; +int flashLength = 0; +unsigned long flashStartTime = 0; +byte flashRed = red; +byte flashGreen = green; +byte flashBlue = blue; +byte flashBrightness = brightness; + + + +WiFiClient espClient; +PubSubClient client(espClient); +DHT dht(DHTPIN, DHTTYPE); +MQ135 gasSensor = MQ135(MQ135PIN); + + +/********************************** START SETUP*****************************************/ +void setup() { + + Serial.begin(115200); + + pinMode(PIRPIN, INPUT); + pinMode(DHTPIN, INPUT); + pinMode(LDRPIN, INPUT); + pinMode(MQ135PIN,INPUT); + + Serial.begin(115200); + delay(10); + + ArduinoOTA.setPort(OTAport); + + ArduinoOTA.setHostname(SENSORNAME); + + ArduinoOTA.setPassword((const char *)OTApassword); + + Serial.print("calibrating sensor "); + for (int i = 0; i < calibrationTime; i++) { + Serial.print("."); + delay(1000); + } + + Serial.println("Starting Node named " + String(SENSORNAME)); + + + setup_wifi(); + + client.setServer(mqtt_server, mqtt_port); + client.setCallback(callback); + + + ArduinoOTA.onStart([]() { + Serial.println("Starting"); + }); + ArduinoOTA.onEnd([]() { + Serial.println("\nEnd"); + }); + ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) { + Serial.printf("Progress: %u%%\r", (progress / (total / 100))); + }); + ArduinoOTA.onError([](ota_error_t error) { + Serial.printf("Error[%u]: ", error); + if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed"); + else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed"); + else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed"); + else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed"); + else if (error == OTA_END_ERROR) Serial.println("End Failed"); + }); + ArduinoOTA.begin(); + Serial.println("Ready"); + Serial.print("IPess: "); + Serial.println(WiFi.localIP()); + reconnect(); +} + + + + +/********************************** START SETUP WIFI*****************************************/ +void setup_wifi() { + + delay(10); + Serial.println(); + Serial.print("Connecting to "); + Serial.println(wifi_ssid); + + WiFi.mode(WIFI_STA); + WiFi.begin(wifi_ssid, wifi_password); + + while (WiFi.status() != WL_CONNECTED) { + delay(500); + Serial.print("."); + } + + Serial.println(""); + Serial.println("WiFi connected"); + Serial.println("IP address: "); + Serial.println(WiFi.localIP()); +} + + + +/********************************** START CALLBACK*****************************************/ +void callback(char* topic, byte* payload, unsigned int length) { + Serial.print("Message arrived ["); + Serial.print(topic); + Serial.print("] "); + + char message[length + 1]; + for (int i = 0; i < length; i++) { + message[i] = (char)payload[i]; + } + message[length] = '\0'; + Serial.println(message); + + if (!processJson(message)) { + return; + } + + if (stateOn) { + // Update lights + realRed = map(red, 0, 255, 0, brightness); + realGreen = map(green, 0, 255, 0, brightness); + realBlue = map(blue, 0, 255, 0, brightness); + } + else { + realRed = 0; + realGreen = 0; + realBlue = 0; + } + + startFade = true; + inFade = false; // Kill the current fade + + sendState(); +} + + + +/********************************** START PROCESS JSON*****************************************/ +bool processJson(char* message) { + StaticJsonBuffer jsonBuffer; + + JsonObject& root = jsonBuffer.parseObject(message); + + if (!root.success()) { + Serial.println("parseObject() failed"); + return false; + } + + if (root.containsKey("state")) { + if (strcmp(root["state"], on_cmd) == 0) { + stateOn = true; + } + else if (strcmp(root["state"], off_cmd) == 0) { + stateOn = false; + } + } + + // If "flash" is included, treat RGB and brightness differently + if (root.containsKey("flash")) { + flashLength = (int)root["flash"] * 1000; + + if (root.containsKey("brightness")) { + flashBrightness = root["brightness"]; + } + else { + flashBrightness = brightness; + } + + if (root.containsKey("color")) { + flashRed = root["color"]["r"]; + flashGreen = root["color"]["g"]; + flashBlue = root["color"]["b"]; + } + else { + flashRed = red; + flashGreen = green; + flashBlue = blue; + } + + flashRed = map(flashRed, 0, 255, 0, flashBrightness); + flashGreen = map(flashGreen, 0, 255, 0, flashBrightness); + flashBlue = map(flashBlue, 0, 255, 0, flashBrightness); + + flash = true; + startFlash = true; + } + else { // Not flashing + flash = false; + + if (root.containsKey("color")) { + red = root["color"]["r"]; + green = root["color"]["g"]; + blue = root["color"]["b"]; + } + + if (root.containsKey("brightness")) { + brightness = root["brightness"]; + } + + if (root.containsKey("transition")) { + transitionTime = root["transition"]; + } + else { + transitionTime = 0; + } + } + + return true; +} + + + +/********************************** START SEND STATE*****************************************/ +void sendState() { + StaticJsonBuffer jsonBuffer; + + JsonObject& root = jsonBuffer.createObject(); + + root["state"] = (stateOn) ? on_cmd : off_cmd; + JsonObject& color = root.createNestedObject("color"); + color["r"] = red; + color["g"] = green; + color["b"] = blue; + + + root["brightness"] = brightness; + root["humidity"] = (String)humValue; + root["motion"] = (String)motionStatus; + root["ldr"] = (String)LDR; + root["temperature"] = (String)tempValue; + root["heatIndex"] = (String)calculateHeatIndex(humValue, tempValue); + root["airquality"] = (String)airQuality; + + + char buffer[root.measureLength() + 1]; + root.printTo(buffer, sizeof(buffer)); + + Serial.println(buffer); + client.publish(light_state_topic, buffer, true); +} + + +/* + * Calculate Heat Index value AKA "Real Feel" + * NOAA heat index calculations taken from + * http://www.wpc.ncep.noaa.gov/html/heatindex_equation.shtml + */ +float calculateHeatIndex(float humidity, float temp) { + float heatIndex= 0; + if (temp >= 80) { + heatIndex = -42.379 + 2.04901523*temp + 10.14333127*humidity; + heatIndex = heatIndex - .22475541*temp*humidity - .00683783*temp*temp; + heatIndex = heatIndex - .05481717*humidity*humidity + .00122874*temp*temp*humidity; + heatIndex = heatIndex + .00085282*temp*humidity*humidity - .00000199*temp*temp*humidity*humidity; + } else { + heatIndex = 0.5 * (temp + 61.0 + ((temp - 68.0)*1.2) + (humidity * 0.094)); + } + + if (humidity < 13 && 80 <= temp <= 112) { + float adjustment = ((13-humidity)/4) * sqrt((17-abs(temp-95.))/17); + heatIndex = heatIndex - adjustment; + } + + return heatIndex; +} + + +/********************************** START SET COLOR *****************************************/ +void setColor(int inR, int inG, int inB) { + analogWrite(redPin, inR); + analogWrite(greenPin, inG); + analogWrite(bluePin, inB); + + Serial.println("Setting LEDs:"); + Serial.print("r: "); + Serial.print(inR); + Serial.print(", g: "); + Serial.print(inG); + Serial.print(", b: "); + Serial.println(inB); +} + + + +/********************************** START RECONNECT*****************************************/ +void reconnect() { + // Loop until we're reconnected + while (!client.connected()) { + Serial.print("Attempting MQTT connection..."); + // Attempt to connect + if (client.connect(SENSORNAME, mqtt_user, mqtt_password)) { + Serial.println("connected"); + client.subscribe(light_set_topic); + setColor(0, 0, 0); + sendState(); + } else { + Serial.print("failed, rc="); + Serial.print(client.state()); + Serial.println(" try again in 5 seconds"); + // Wait 5 seconds before retrying + delay(5000); + } + } +} + + + +/********************************** START CHECK SENSOR **********************************/ +bool checkBoundSensor(float newValue, float prevValue, float maxDiff) { + return newValue < prevValue - maxDiff || newValue > prevValue + maxDiff; +} + + +/********************************** START MAIN LOOP***************************************/ +void loop() { + + ArduinoOTA.handle(); + + if (!client.connected()) { + // reconnect(); + software_Reset(); + } + client.loop(); + + if (!inFade) { + + float newTempValue = dht.readTemperature(true); //to use celsius remove the true text inside the parentheses + float newHumValue = dht.readHumidity(); + + float newAirQuality = gasSensor.getPPM(); // read out of the gas sensor + + //PIR CODE + pirValue = digitalRead(PIRPIN); //read state of the + + if (pirValue == LOW && pirStatus != 1) { + motionStatus = "standby"; + sendState(); + pirStatus = 1; + } + + else if (pirValue == HIGH && pirStatus != 2) { + motionStatus = "motion detected"; + sendState(); + pirStatus = 2; + } + + delay(100); + + if (checkBoundSensor(newTempValue, tempValue, diffTEMP)) { + tempValue = newTempValue; + sendState(); + } + + if (checkBoundSensor(newHumValue, humValue, diffHUM)) { + humValue = newHumValue; + sendState(); + } + + if (checkBoundSensor(newAirQuality, airQuality, diffAQ)) { + airQuality = newAirQuality; + sendState(); + } + + + int newLDR = analogRead(LDRPIN); + + if (checkBoundSensor(newLDR, LDR, diffLDR)) { + LDR = newLDR; + sendState(); + } + + } + + if (flash) { + if (startFlash) { + startFlash = false; + flashStartTime = millis(); + } + + if ((millis() - flashStartTime) <= flashLength) { + if ((millis() - flashStartTime) % 1000 <= 500) { + setColor(flashRed, flashGreen, flashBlue); + } + else { + setColor(0, 0, 0); + // If you'd prefer the flashing to happen "on top of" + // the current color, uncomment the next line. + // setColor(realRed, realGreen, realBlue); + } + } + else { + flash = false; + setColor(realRed, realGreen, realBlue); + } + } + + if (startFade) { + // If we don't want to fade, skip it. + if (transitionTime == 0) { + setColor(realRed, realGreen, realBlue); + + redVal = realRed; + grnVal = realGreen; + bluVal = realBlue; + + startFade = false; + } + else { + loopCount = 0; + stepR = calculateStep(redVal, realRed); + stepG = calculateStep(grnVal, realGreen); + stepB = calculateStep(bluVal, realBlue); + + inFade = true; + } + } + + if (inFade) { + startFade = false; + unsigned long now = millis(); + if (now - lastLoop > transitionTime) { + if (loopCount <= 1020) { + lastLoop = now; + + redVal = calculateVal(stepR, redVal, loopCount); + grnVal = calculateVal(stepG, grnVal, loopCount); + bluVal = calculateVal(stepB, bluVal, loopCount); + + setColor(redVal, grnVal, bluVal); // Write current values to LED pins + + Serial.print("Loop count: "); + Serial.println(loopCount); + loopCount++; + } + else { + inFade = false; + } + } + } +} + + + + +/**************************** START TRANSITION FADER *****************************************/ +// From https://www.arduino.cc/en/Tutorial/ColorCrossfader +/* BELOW THIS LINE IS THE MATH -- YOU SHOULDN'T NEED TO CHANGE THIS FOR THE BASICS + + The program works like this: + Imagine a crossfade that moves the red LED from 0-10, + the green from 0-5, and the blue from 10 to 7, in + ten steps. + We'd want to count the 10 steps and increase or + decrease color values in evenly stepped increments. + Imagine a + indicates raising a value by 1, and a - + equals lowering it. Our 10 step fade would look like: + + 1 2 3 4 5 6 7 8 9 10 + R + + + + + + + + + + + G + + + + + + B - - - + + The red rises from 0 to 10 in ten steps, the green from + 0-5 in 5 steps, and the blue falls from 10 to 7 in three steps. + + In the real program, the color percentages are converted to + 0-255 values, and there are 1020 steps (255*4). + + To figure out how big a step there should be between one up- or + down-tick of one of the LED values, we call calculateStep(), + which calculates the absolute gap between the start and end values, + and then divides that gap by 1020 to determine the size of the step + between adjustments in the value. +*/ +int calculateStep(int prevValue, int endValue) { + int step = endValue - prevValue; // What's the overall gap? + if (step) { // If its non-zero, + step = 1020 / step; // divide by 1020 + } + + return step; +} + +/* The next function is calculateVal. When the loop value, i, + reaches the step size appropriate for one of the + colors, it increases or decreases the value of that color by 1. + (R, G, and B are each calculated separately.) +*/ +int calculateVal(int step, int val, int i) { + if ((step) && i % step == 0) { // If step is non-zero and its time to change a value, + if (step > 0) { // increment the value if step is positive... + val += 1; + } + else if (step < 0) { // ...or decrement it if step is negative + val -= 1; + } + } + + // Defensive driving: make sure val stays in the range 0-255 + if (val > 255) { + val = 255; + } + else if (val < 0) { + val = 0; + } + + return val; +} + +/****reset***/ +void software_Reset() // Restarts program from beginning but does not reset the peripherals and registers +{ +Serial.print("resetting"); +ESP.reset(); } From 4262daff38c93cb34e4a8b9c3e549d4394ce0e53 Mon Sep 17 00:00:00 2001 From: Chris Date: Thu, 20 Jul 2017 07:43:36 -0700 Subject: [PATCH 2/6] Variable fixes --- bruh_mqtt_multisensor_github/bruh_mqtt_multisensor_github.ino | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/bruh_mqtt_multisensor_github/bruh_mqtt_multisensor_github.ino b/bruh_mqtt_multisensor_github/bruh_mqtt_multisensor_github.ino index dfbf4fd..5f5eb54 100644 --- a/bruh_mqtt_multisensor_github/bruh_mqtt_multisensor_github.ino +++ b/bruh_mqtt_multisensor_github/bruh_mqtt_multisensor_github.ino @@ -101,6 +101,10 @@ const int BUFFER_SIZE = 300; #define MQTT_MAX_PACKET_SIZE 512 +// MQ-135 variables +float diffAQ = 0.1; // sensitivity to report new update +float airQuality; + /******************************** GLOBALS for fade/flash *******************************/ byte red = 255; From fdbe16342ae482904785169e6054b812c6790fa0 Mon Sep 17 00:00:00 2001 From: Chris Date: Thu, 20 Jul 2017 11:35:47 -0700 Subject: [PATCH 3/6] Update for multiple MQ sensors * Added define for MQ2 Sensors * Added define for MQ135 Sensors --- .../bruh_mqtt_multisensor_github.ino | 94 +++++++++++++++---- 1 file changed, 78 insertions(+), 16 deletions(-) diff --git a/bruh_mqtt_multisensor_github/bruh_mqtt_multisensor_github.ino b/bruh_mqtt_multisensor_github/bruh_mqtt_multisensor_github.ino index 5f5eb54..dcdd3b6 100644 --- a/bruh_mqtt_multisensor_github/bruh_mqtt_multisensor_github.ino +++ b/bruh_mqtt_multisensor_github/bruh_mqtt_multisensor_github.ino @@ -19,15 +19,13 @@ - Adafruit unified sensor - PubSubClient - ArduinoJSON - + UPDATE 16 MAY 2017 by Knutella - Fixed MQTT disconnects when wifi drops by moving around Reconnect and adding a software reset of MCU - + UPDATE 23 MAY 2017 - The MQTT_MAX_PACKET_SIZE parameter may not be setting appropriately do to a bug in the PubSub library. If the MQTT messages are not being transmitted as expected please you may need to change the MQTT_MAX_PACKET_SIZE parameter in "PubSubClient.h" directly. */ - - #include #include #include @@ -35,8 +33,19 @@ #include #include #include -#include +/* + * Uncomment to enable MQ type sensor +*/ + +//#define MY_MQ2 +//#define MY_MQ135 + +#if defined(MY_MQ2) +#include +#elif defined(MY_MQ135) +#include +#endif /************ WIFI and MQTT INFORMATION (CHANGE THESE FOR YOUR SETUP) ******************/ @@ -73,7 +82,13 @@ const int bluePin = D3; #define DHTPIN D7 #define DHTTYPE DHT22 #define LDRPIN A0 + +#if defined(MY_MQ2) +#define MQ2PIN A1 // change this to pin of the MQ2 +#elif defined(MY_MQ135) #define MQ135PIN A1 // change this to the pin of the MQ135 +#endif + @@ -101,9 +116,17 @@ const int BUFFER_SIZE = 300; #define MQTT_MAX_PACKET_SIZE 512 -// MQ-135 variables +#if defined(MY_MQ2) +int lpg, co, smoke; +int diffLPG = 1; +int diffCO = 1; +int diffSmoke = 1; + +#elif defined(MY_MQ135) float diffAQ = 0.1; // sensitivity to report new update float airQuality; +#endif + /******************************** GLOBALS for fade/flash *******************************/ @@ -140,9 +163,14 @@ byte flashBrightness = brightness; WiFiClient espClient; PubSubClient client(espClient); DHT dht(DHTPIN, DHTTYPE); -MQ135 gasSensor = MQ135(MQ135PIN); +#if defined(MY_MQ2) +MQ2 mq2(MQ2PIN); +#elif defined(MY_MQ135) +MQ135 gasSensor = MQ135(MQ135PIN); +#endif + /********************************** START SETUP*****************************************/ void setup() { @@ -151,8 +179,15 @@ void setup() { pinMode(PIRPIN, INPUT); pinMode(DHTPIN, INPUT); pinMode(LDRPIN, INPUT); + + #if defined(MY_MQ135) pinMode(MQ135PIN,INPUT); - + #endif + + #if defined(MY_MQ2) + mq2.begin(); + #endif + Serial.begin(115200); delay(10); @@ -359,8 +394,13 @@ void sendState() { root["ldr"] = (String)LDR; root["temperature"] = (String)tempValue; root["heatIndex"] = (String)calculateHeatIndex(humValue, tempValue); + #if defined(MY_MQ2) + root["lpg"] = (String)lpg; + root["co"] = (String)co; + root["smoke"] = (String)smoke; + #elif defined(MY_MQ135) root["airquality"] = (String)airQuality; - + #endif char buffer[root.measureLength() + 1]; root.printTo(buffer, sizeof(buffer)); @@ -456,9 +496,37 @@ void loop() { float newTempValue = dht.readTemperature(true); //to use celsius remove the true text inside the parentheses float newHumValue = dht.readHumidity(); - + + #if defined(MY_MQ2) + int newLPG = mq2.readLPG(); + int newCO = mq2.readCO(); + int newSmoke = mq2.readSmoke(); + + if (checkBoundSensor(newLPG, lpg, diffLPG)) { + lpg = newLPG; + sendState(); + } + if (checkBoundSensor(newCO, co, diffCO)) { + co = newCO; + sendState(); + } + if (checkBoundSensor(newSmoke, smoke, diffSmoke)) { + smoke = newSmoke; + sendState(); + } + + #elif defined(MY_MQ135) + float newAirQuality = gasSensor.getPPM(); // read out of the gas sensor + if (checkBoundSensor(newAirQuality, airQuality, diffAQ)) { + airQuality = newAirQuality; + sendState(); + } + + #endif + + //PIR CODE pirValue = digitalRead(PIRPIN); //read state of the @@ -486,12 +554,6 @@ void loop() { sendState(); } - if (checkBoundSensor(newAirQuality, airQuality, diffAQ)) { - airQuality = newAirQuality; - sendState(); - } - - int newLDR = analogRead(LDRPIN); if (checkBoundSensor(newLDR, LDR, diffLDR)) { From 1a6561723575002a091f61e1b3f5d68575d74f07 Mon Sep 17 00:00:00 2001 From: Chris Date: Mon, 31 Jul 2017 08:13:55 -0700 Subject: [PATCH 4/6] Removed unneeded pinMode --- bruh_mqtt_multisensor_github/bruh_mqtt_multisensor_github.ino | 4 ---- 1 file changed, 4 deletions(-) diff --git a/bruh_mqtt_multisensor_github/bruh_mqtt_multisensor_github.ino b/bruh_mqtt_multisensor_github/bruh_mqtt_multisensor_github.ino index dcdd3b6..88cb7c3 100644 --- a/bruh_mqtt_multisensor_github/bruh_mqtt_multisensor_github.ino +++ b/bruh_mqtt_multisensor_github/bruh_mqtt_multisensor_github.ino @@ -180,10 +180,6 @@ void setup() { pinMode(DHTPIN, INPUT); pinMode(LDRPIN, INPUT); - #if defined(MY_MQ135) - pinMode(MQ135PIN,INPUT); - #endif - #if defined(MY_MQ2) mq2.begin(); #endif From 2186ce7f3ec08b3b7b1ac622fdcdca354fe5e41a Mon Sep 17 00:00:00 2001 From: Chris Date: Tue, 28 Nov 2017 16:03:25 -0700 Subject: [PATCH 5/6] Should support all MQ sensors Returns in PPM * LPG * CO * Smoke --- .../bruh_mqtt_multisensor_github.ino | 204 ++++++++++++++---- 1 file changed, 159 insertions(+), 45 deletions(-) diff --git a/bruh_mqtt_multisensor_github/bruh_mqtt_multisensor_github.ino b/bruh_mqtt_multisensor_github/bruh_mqtt_multisensor_github.ino index 88cb7c3..82c5869 100644 --- a/bruh_mqtt_multisensor_github/bruh_mqtt_multisensor_github.ino +++ b/bruh_mqtt_multisensor_github/bruh_mqtt_multisensor_github.ino @@ -38,13 +38,48 @@ * Uncomment to enable MQ type sensor */ -//#define MY_MQ2 -//#define MY_MQ135 +//#define ENABLE_MQ -#if defined(MY_MQ2) -#include -#elif defined(MY_MQ135) -#include +#ifdef ENABLE_MQ +int lpg, co, smoke; +int diffLPG = 1; +int diffCO = 1; +int diffSmoke = 1; + +/************************Hardware Related Macros************************************/ +#define MQ_SENSOR_ANALOG_PIN (2) //define which analog input channel you are going to use +#define RL_VALUE (5) //define the load resistance on the board, in kilo ohms +#define RO_CLEAN_AIR_FACTOR (9.83) //RO_CLEAR_AIR_FACTOR=(Sensor resistance in clean air)/RO, +//which is derived from the chart in datasheet +/***********************Software Related Macros************************************/ +#define CALIBARAION_SAMPLE_TIMES (50) //define how many samples you are going to take in the calibration phase +#define CALIBRATION_SAMPLE_INTERVAL (500) //define the time interal(in milisecond) between each samples in the +//cablibration phase +#define READ_SAMPLE_INTERVAL (50) //define how many samples you are going to take in normal operation +#define READ_SAMPLE_TIMES (5) //define the time interal(in milisecond) between each samples in +//normal operation +/**********************Application Related Macros**********************************/ +#define GAS_LPG (0) +#define GAS_CO (1) +#define GAS_SMOKE (2) +/*****************************Globals***********************************************/ +//VARIABLES +float Ro = 10000.0; // this has to be tuned 10K Ohm +int val = 0; // variable to store the value coming from the sensor +float valMQ =0.0; +float lastMQ =0.0; +float LPGCurve[3] = {2.3,0.21,-0.47}; //two points are taken from the curve. +//with these two points, a line is formed which is "approximately equivalent" +//to the original curve. +//data format:{ x, y, slope}; point1: (lg200, 0.21), point2: (lg10000, -0.59) +float COCurve[3] = {2.3,0.72,-0.34}; //two points are taken from the curve. +//with these two points, a line is formed which is "approximately equivalent" +//to the original curve. +//data format:{ x, y, slope}; point1: (lg200, 0.72), point2: (lg10000, 0.15) +float SmokeCurve[3] = {2.3,0.53,-0.44}; //two points are taken from the curve. +//with these two points, a line is formed which is "approximately equivalent" +//to the original curve. +//data format:{ x, y, slope}; point1: (lg200, 0.53), point2:(lg10000,-0.22) #endif @@ -116,19 +151,6 @@ const int BUFFER_SIZE = 300; #define MQTT_MAX_PACKET_SIZE 512 -#if defined(MY_MQ2) -int lpg, co, smoke; -int diffLPG = 1; -int diffCO = 1; -int diffSmoke = 1; - -#elif defined(MY_MQ135) -float diffAQ = 0.1; // sensitivity to report new update -float airQuality; -#endif - - - /******************************** GLOBALS for fade/flash *******************************/ byte red = 255; byte green = 255; @@ -164,13 +186,6 @@ WiFiClient espClient; PubSubClient client(espClient); DHT dht(DHTPIN, DHTTYPE); - -#if defined(MY_MQ2) -MQ2 mq2(MQ2PIN); -#elif defined(MY_MQ135) -MQ135 gasSensor = MQ135(MQ135PIN); -#endif - /********************************** START SETUP*****************************************/ void setup() { @@ -390,14 +405,11 @@ void sendState() { root["ldr"] = (String)LDR; root["temperature"] = (String)tempValue; root["heatIndex"] = (String)calculateHeatIndex(humValue, tempValue); - #if defined(MY_MQ2) + #ifdef ENABLE_MQ root["lpg"] = (String)lpg; root["co"] = (String)co; root["smoke"] = (String)smoke; - #elif defined(MY_MQ135) - root["airquality"] = (String)airQuality; #endif - char buffer[root.measureLength() + 1]; root.printTo(buffer, sizeof(buffer)); @@ -493,10 +505,26 @@ void loop() { float newTempValue = dht.readTemperature(true); //to use celsius remove the true text inside the parentheses float newHumValue = dht.readHumidity(); - #if defined(MY_MQ2) - int newLPG = mq2.readLPG(); - int newCO = mq2.readCO(); - int newSmoke = mq2.readSmoke(); + #ifdef ENABLE_MQ + uint16_t co = MQGetGasPercentage(MQRead(MQ_SENSOR_ANALOG_PIN)/Ro,GAS_CO); + uint16_t lpg = MQGetGasPercentage(MQRead(MQ_SENSOR_ANALOG_PIN)/Ro,GAS_LPG); + uint16_t smoke = MQGetGasPercentage(MQRead(MQ_SENSOR_ANALOG_PIN)/Ro,GAS_SMOKE); + #ifdef MY_DEBUG + Serial.println(val); + + Serial.print("LPG:"); + Serial.print(MQGetGasPercentage(MQRead(MQ_SENSOR_ANALOG_PIN)/Ro,GAS_LPG) ); + Serial.print( "ppm" ); + Serial.print(" "); + Serial.print("CO:"); + Serial.print(MQGetGasPercentage(MQRead(MQ_SENSOR_ANALOG_PIN)/Ro,GAS_CO) ); + Serial.print( "ppm" ); + Serial.print(" "); + Serial.print("SMOKE:"); + Serial.print(MQGetGasPercentage(MQRead(MQ_SENSOR_ANALOG_PIN)/Ro,GAS_SMOKE) ); + Serial.print( "ppm" ); + Serial.print("\n"); + #endif if (checkBoundSensor(newLPG, lpg, diffLPG)) { lpg = newLPG; @@ -510,17 +538,8 @@ void loop() { smoke = newSmoke; sendState(); } - - #elif defined(MY_MQ135) - - float newAirQuality = gasSensor.getPPM(); // read out of the gas sensor - if (checkBoundSensor(newAirQuality, airQuality, diffAQ)) { - airQuality = newAirQuality; - sendState(); - } - - #endif + #endif //PIR CODE @@ -700,4 +719,99 @@ void software_Reset() // Restarts program from beginning but does not reset the { Serial.print("resetting"); ESP.reset(); -} +} + +#ifdef ENABLE_MQ +/****************** MQResistanceCalculation **************************************** +Input: raw_adc - raw value read from adc, which represents the voltage +Output: the calculated sensor resistance +Remarks: The sensor and the load resistor forms a voltage divider. Given the voltage + across the load resistor and its resistance, the resistance of the sensor + could be derived. +************************************************************************************/ +float MQResistanceCalculation(int raw_adc) +{ + return ( ((float)RL_VALUE*(1023-raw_adc)/raw_adc)); +} + +/***************************** MQCalibration **************************************** +Input: mq_pin - analog channel +Output: Ro of the sensor +Remarks: This function assumes that the sensor is in clean air. It use + MQResistanceCalculation to calculates the sensor resistance in clean air + and then divides it with RO_CLEAN_AIR_FACTOR. RO_CLEAN_AIR_FACTOR is about + 10, which differs slightly between different sensors. +************************************************************************************/ +float MQCalibration(int mq_pin) +{ + int i; + float val=0; + + for (i=0; i Date: Wed, 29 Nov 2017 05:34:47 -0700 Subject: [PATCH 6/6] Removed unused variables --- .../bruh_mqtt_multisensor_github.ino | 9 --------- 1 file changed, 9 deletions(-) diff --git a/bruh_mqtt_multisensor_github/bruh_mqtt_multisensor_github.ino b/bruh_mqtt_multisensor_github/bruh_mqtt_multisensor_github.ino index 82c5869..015950d 100644 --- a/bruh_mqtt_multisensor_github/bruh_mqtt_multisensor_github.ino +++ b/bruh_mqtt_multisensor_github/bruh_mqtt_multisensor_github.ino @@ -118,15 +118,6 @@ const int bluePin = D3; #define DHTTYPE DHT22 #define LDRPIN A0 -#if defined(MY_MQ2) -#define MQ2PIN A1 // change this to pin of the MQ2 -#elif defined(MY_MQ135) -#define MQ135PIN A1 // change this to the pin of the MQ135 -#endif - - - - /**************************** SENSOR DEFINITIONS *******************************************/ float ldrValue; int LDR;