Advertisement
Guest User

Bruh Sensor Node with Push Button

a guest
Jun 26th, 2017
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 17.74 KB | None | 0 0
  1. /*
  2. .______ .______ __ __ __ __ ___ __ __ .___________. ______ .___ ___. ___ .___________. __ ______ .__ __.
  3. | _ \ | _ \ | | | | | | | | / \ | | | | | | / __ \ | \/ | / \ | || | / __ \ | \ | |
  4. | |_) | | |_) | | | | | | |__| | / ^ \ | | | | `---| |----`| | | | | \ / | / ^ \ `---| |----`| | | | | | | \| |
  5. | _ < | / | | | | | __ | / /_\ \ | | | | | | | | | | | |\/| | / /_\ \ | | | | | | | | | . ` |
  6. | |_) | | |\ \-.| `--' | | | | | / _____ \ | `--' | | | | `--' | | | | | / _____ \ | | | | | `--' | | |\ |
  7. |______/ | _| `.__| \______/ |__| |__| /__/ \__\ \______/ |__| \______/ |__| |__| /__/ \__\ |__| |__| \______/ |__| \__|
  8.  
  9. Thanks much to @corbanmailloux for providing a great framework for implementing flash/fade with HomeAssistant https://github.com/corbanmailloux/esp-mqtt-rgb-led
  10.  
  11. To use this code you will need the following dependancies:
  12.  
  13. - Support for the ESP8266 boards.
  14. - 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.
  15. - Next, download the ESP8266 dependancies by going to Tools -> Board -> Board Manager and searching for ESP8266 and installing it.
  16.  
  17. - You will also need to download the follow libraries by going to Sketch -> Include Libraries -> Manage Libraries
  18. - DHT sensor library
  19. - Adfruit unified sensor
  20. - PubSubClient
  21. - ArduinoJSON
  22.  
  23. */
  24.  
  25.  
  26.  
  27. #include <ESP8266WiFi.h>
  28. #include <DHT.h>
  29. #include <PubSubClient.h>
  30. #include <ESP8266mDNS.h>
  31. #include <WiFiUdp.h>
  32. #include <ArduinoOTA.h>
  33. #include <ArduinoJson.h>
  34.  
  35.  
  36.  
  37. /************ WIFI and MQTT INFORMATION (CHANGE THESE FOR YOUR SETUP) ******************/
  38. #define wifi_ssid "_wifi_" //type your WIFI information inside the quotes
  39. #define wifi_password "_password_"
  40. #define mqtt_server "_mqtt_server_"
  41. #define mqtt_user "_username_"
  42. #define mqtt_password "_password_"
  43. #define mqtt_port 1883
  44.  
  45.  
  46.  
  47. /************* MQTT TOPICS (change these topics as you wish) **************************/
  48. #define light_state_topic "home/shed"
  49. #define light_set_topic "home/shed/set"
  50.  
  51. const char* on_cmd = "ON";
  52. const char* off_cmd = "OFF";
  53.  
  54.  
  55.  
  56. /**************************** FOR OTA **************************************************/
  57. #define SENSORNAME "sensor-shed"
  58. #define OTApassword "_ota_password_" // change this to whatever password you want to use when you upload OTA
  59. int OTAport = 8266;
  60.  
  61.  
  62.  
  63. /**************************** PIN DEFINITIONS ********************************************/
  64. const int redPin = D1;
  65. const int greenPin = D2;
  66. const int bluePin = D3;
  67.  
  68. /***Added for button***/
  69. const int buttonPin = D6;
  70.  
  71. #define PIRPIN D5
  72. #define DHTPIN D7
  73. #define DHTTYPE DHT22
  74. #define LDRPIN A0
  75.  
  76.  
  77.  
  78. /**************************** SENSOR DEFINITIONS *******************************************/
  79. float ldrValue;
  80. int LDR;
  81. float calcLDR;
  82. float diffLDR = 25;
  83.  
  84. /***Added for button***/
  85.  
  86. // the current state of the LED and button
  87.  
  88. int buttonState = LOW;
  89.  
  90. // the current and previous readings from the input pin
  91. int thisButtonState = LOW;
  92. int lastButtonState = LOW;
  93.  
  94. // time is measured in milliseconds and will quickly exceed limitations of an integer, so we use a long for these two
  95. unsigned long lastDebounceTime = 0; // the time the button state last switched
  96. unsigned long debounceDelay = 50; // the state must remain the same for this many millis to register the button press
  97.  
  98. String pressStatus;
  99.  
  100. float diffTEMP = 0.2;
  101. float tempValue;
  102.  
  103. float diffHUM = 1;
  104. float humValue;
  105.  
  106. int pirValue;
  107. int pirStatus;
  108. String motionStatus;
  109.  
  110. char message_buff[100];
  111.  
  112. int calibrationTime = 0;
  113.  
  114. const int BUFFER_SIZE = 300;
  115.  
  116. #define MQTT_MAX_PACKET_SIZE 512
  117.  
  118.  
  119. /******************************** GLOBALS for fade/flash *******************************/
  120. byte red = 255;
  121. byte green = 255;
  122. byte blue = 255;
  123. byte brightness = 255;
  124.  
  125. byte realRed = 0;
  126. byte realGreen = 0;
  127. byte realBlue = 0;
  128.  
  129. bool stateOn = false;
  130.  
  131. bool startFade = false;
  132. unsigned long lastLoop = 0;
  133. int transitionTime = 0;
  134. bool inFade = false;
  135. int loopCount = 0;
  136. int stepR, stepG, stepB;
  137. int redVal, grnVal, bluVal;
  138.  
  139. bool flash = false;
  140. bool startFlash = false;
  141. int flashLength = 0;
  142. unsigned long flashStartTime = 0;
  143. byte flashRed = red;
  144. byte flashGreen = green;
  145. byte flashBlue = blue;
  146. byte flashBrightness = brightness;
  147.  
  148.  
  149.  
  150. WiFiClient espClient;
  151. PubSubClient client(espClient);
  152. DHT dht(DHTPIN, DHTTYPE);
  153.  
  154.  
  155.  
  156. /********************************** START SETUP*****************************************/
  157. void setup() {
  158.  
  159. Serial.begin(115200);
  160.  
  161. pinMode(PIRPIN, INPUT);
  162. pinMode(DHTPIN, INPUT);
  163. pinMode(LDRPIN, INPUT);
  164.  
  165. /***Added for button***/
  166. pinMode(buttonPin, INPUT);
  167.  
  168. Serial.begin(115200);
  169. delay(10);
  170.  
  171. ArduinoOTA.setPort(OTAport);
  172.  
  173. ArduinoOTA.setHostname(SENSORNAME);
  174.  
  175. ArduinoOTA.setPassword((const char *)OTApassword);
  176.  
  177. Serial.print("calibrating sensor ");
  178. for (int i = 0; i < calibrationTime; i++) {
  179. Serial.print(".");
  180. delay(1000);
  181. }
  182.  
  183. Serial.println("Starting Node named " + String(SENSORNAME));
  184.  
  185.  
  186. setup_wifi();
  187.  
  188. client.setServer(mqtt_server, mqtt_port);
  189. client.setCallback(callback);
  190.  
  191.  
  192. ArduinoOTA.onStart([]() {
  193. Serial.println("Starting");
  194. });
  195. ArduinoOTA.onEnd([]() {
  196. Serial.println("\nEnd");
  197. });
  198. ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
  199. Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
  200. });
  201. ArduinoOTA.onError([](ota_error_t error) {
  202. Serial.printf("Error[%u]: ", error);
  203. if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed");
  204. else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed");
  205. else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed");
  206. else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed");
  207. else if (error == OTA_END_ERROR) Serial.println("End Failed");
  208. });
  209. ArduinoOTA.begin();
  210. Serial.println("Ready");
  211. Serial.print("IPess: ");
  212. Serial.println(WiFi.localIP());
  213. reconnect();
  214. }
  215.  
  216.  
  217.  
  218.  
  219. /********************************** START SETUP WIFI*****************************************/
  220. void setup_wifi() {
  221.  
  222. delay(10);
  223. Serial.println();
  224. Serial.print("Connecting to ");
  225. Serial.println(wifi_ssid);
  226.  
  227. WiFi.mode(WIFI_STA);
  228. WiFi.begin(wifi_ssid, wifi_password);
  229.  
  230. while (WiFi.status() != WL_CONNECTED) {
  231. delay(500);
  232. Serial.print(".");
  233. }
  234.  
  235. Serial.println("");
  236. Serial.println("WiFi connected");
  237. Serial.println("IP address: ");
  238. Serial.println(WiFi.localIP());
  239. }
  240.  
  241.  
  242.  
  243. /********************************** START CALLBACK*****************************************/
  244. void callback(char* topic, byte* payload, unsigned int length) {
  245. Serial.print("Message arrived [");
  246. Serial.print(topic);
  247. Serial.print("] ");
  248.  
  249. char message[length + 1];
  250. for (int i = 0; i < length; i++) {
  251. message[i] = (char)payload[i];
  252. }
  253. message[length] = '\0';
  254. Serial.println(message);
  255.  
  256. if (!processJson(message)) {
  257. return;
  258. }
  259.  
  260. if (stateOn) {
  261. // Update lights
  262. realRed = map(red, 0, 255, 0, brightness);
  263. realGreen = map(green, 0, 255, 0, brightness);
  264. realBlue = map(blue, 0, 255, 0, brightness);
  265. }
  266. else {
  267. realRed = 0;
  268. realGreen = 0;
  269. realBlue = 0;
  270. }
  271.  
  272. startFade = true;
  273. inFade = false; // Kill the current fade
  274.  
  275. sendState();
  276. }
  277.  
  278.  
  279.  
  280. /********************************** START PROCESS JSON*****************************************/
  281. bool processJson(char* message) {
  282. StaticJsonBuffer<BUFFER_SIZE> jsonBuffer;
  283.  
  284. JsonObject& root = jsonBuffer.parseObject(message);
  285.  
  286. if (!root.success()) {
  287. Serial.println("parseObject() failed");
  288. return false;
  289. }
  290.  
  291. if (root.containsKey("state")) {
  292. if (strcmp(root["state"], on_cmd) == 0) {
  293. stateOn = true;
  294. }
  295. else if (strcmp(root["state"], off_cmd) == 0) {
  296. stateOn = false;
  297. }
  298. }
  299.  
  300. // If "flash" is included, treat RGB and brightness differently
  301. if (root.containsKey("flash")) {
  302. flashLength = (int)root["flash"] * 1000;
  303.  
  304. if (root.containsKey("brightness")) {
  305. flashBrightness = root["brightness"];
  306. }
  307. else {
  308. flashBrightness = brightness;
  309. }
  310.  
  311. if (root.containsKey("color")) {
  312. flashRed = root["color"]["r"];
  313. flashGreen = root["color"]["g"];
  314. flashBlue = root["color"]["b"];
  315. }
  316. else {
  317. flashRed = red;
  318. flashGreen = green;
  319. flashBlue = blue;
  320. }
  321.  
  322. flashRed = map(flashRed, 0, 255, 0, flashBrightness);
  323. flashGreen = map(flashGreen, 0, 255, 0, flashBrightness);
  324. flashBlue = map(flashBlue, 0, 255, 0, flashBrightness);
  325.  
  326. flash = true;
  327. startFlash = true;
  328. }
  329. else { // Not flashing
  330. flash = false;
  331.  
  332. if (root.containsKey("color")) {
  333. red = root["color"]["r"];
  334. green = root["color"]["g"];
  335. blue = root["color"]["b"];
  336. }
  337.  
  338. if (root.containsKey("brightness")) {
  339. brightness = root["brightness"];
  340. }
  341.  
  342. if (root.containsKey("transition")) {
  343. transitionTime = root["transition"];
  344. }
  345. else {
  346. transitionTime = 0;
  347. }
  348. }
  349.  
  350. return true;
  351. }
  352.  
  353.  
  354.  
  355. /********************************** START SEND STATE*****************************************/
  356. void sendState() {
  357. StaticJsonBuffer<BUFFER_SIZE> jsonBuffer;
  358.  
  359. JsonObject& root = jsonBuffer.createObject();
  360.  
  361. root["state"] = (stateOn) ? on_cmd : off_cmd;
  362. JsonObject& color = root.createNestedObject("color");
  363. color["r"] = red;
  364. color["g"] = green;
  365. color["b"] = blue;
  366.  
  367.  
  368. root["brightness"] = brightness;
  369. root["humidity"] = (String)humValue;
  370. root["motion"] = (String)motionStatus;
  371. root["ldr"] = (String)LDR;
  372. root["temperature"] = (String)tempValue;
  373.  
  374. /***Added for button***/
  375. root["button"] = (String)pressStatus;
  376.  
  377. char buffer[root.measureLength() + 1];
  378. root.printTo(buffer, sizeof(buffer));
  379.  
  380. Serial.println(buffer);
  381. client.publish(light_state_topic, buffer, true);
  382. }
  383.  
  384.  
  385. /********************************** START SET COLOR *****************************************/
  386. void setColor(int inR, int inG, int inB) {
  387. analogWrite(redPin, inR);
  388. analogWrite(greenPin, inG);
  389. analogWrite(bluePin, inB);
  390.  
  391. Serial.println("Setting LEDs:");
  392. Serial.print("r: ");
  393. Serial.print(inR);
  394. Serial.print(", g: ");
  395. Serial.print(inG);
  396. Serial.print(", b: ");
  397. Serial.println(inB);
  398. }
  399.  
  400.  
  401.  
  402. /********************************** START RECONNECT*****************************************/
  403. void reconnect() {
  404. // Loop until we're reconnected
  405. while (!client.connected()) {
  406. Serial.print("Attempting MQTT connection...");
  407. // Attempt to connect
  408. if (client.connect(SENSORNAME, mqtt_user, mqtt_password)) {
  409. Serial.println("connected");
  410. client.subscribe(light_set_topic);
  411. setColor(0, 0, 0);
  412. sendState();
  413. } else {
  414. Serial.print("failed, rc=");
  415. Serial.print(client.state());
  416. Serial.println(" try again in 5 seconds");
  417. // Wait 5 seconds before retrying
  418. delay(5000);
  419. }
  420. }
  421. }
  422.  
  423.  
  424.  
  425. /********************************** START CHECK SENSOR **********************************/
  426. bool checkBoundSensor(float newValue, float prevValue, float maxDiff) {
  427. return newValue < prevValue - maxDiff || newValue > prevValue + maxDiff;
  428. }
  429.  
  430.  
  431.  
  432. /********************************** START MAIN LOOP***************************************/
  433. void loop() {
  434.  
  435. ArduinoOTA.handle();
  436.  
  437. if (!client.connected()) {
  438. // reconnect();
  439. software_Reset();
  440. }
  441. client.loop();
  442.  
  443.  
  444. if (!inFade) {
  445.  
  446. float newTempValue = dht.readTemperature(true);
  447. float newHumValue = dht.readHumidity();
  448.  
  449. //BUTTON CODE
  450.  
  451. // the buttonPin is read multiple times and the value must remain the same for debounceDelay millis to toggle the LED
  452.  
  453. // read button state, HIGH when pressed, LOW when not
  454. thisButtonState = digitalRead(buttonPin);
  455.  
  456. // if the current state does not match the previous state
  457. // the button was just pressed/released, or is transition noise
  458. if (thisButtonState != lastButtonState) {
  459. // reset the timer
  460. lastDebounceTime = millis();
  461. }
  462.  
  463. // once delay millis have elapsed, if the state remains the same, register the press
  464. if ((millis() - lastDebounceTime) > debounceDelay) {
  465.  
  466. // if the button state has changed
  467. if (thisButtonState != buttonState) {
  468. buttonState = thisButtonState;
  469.  
  470. // only toggle the LED if the buttonState has switched from LOW to HIGH
  471. if (buttonState == HIGH) {
  472. pressStatus = "off";
  473. sendState();
  474.  
  475. }
  476. else {
  477. pressStatus = "on";
  478. sendState();
  479.  
  480. }
  481. }
  482. }
  483.  
  484. lastButtonState = thisButtonState;
  485. delay(100);
  486.  
  487. //PIR CODE
  488. pirValue = digitalRead(PIRPIN); //read state of the
  489.  
  490. if (pirValue == LOW && pirStatus != 1) {
  491. motionStatus = "standby";
  492. sendState();
  493. pirStatus = 1;
  494. }
  495.  
  496. else if (pirValue == HIGH && pirStatus != 2) {
  497. motionStatus = "motion detected";
  498. sendState();
  499. pirStatus = 2;
  500. }
  501.  
  502. delay(100);
  503.  
  504. if (checkBoundSensor(newTempValue, tempValue, diffTEMP)) {
  505. tempValue = newTempValue;
  506. sendState();
  507. }
  508.  
  509. if (checkBoundSensor(newHumValue, humValue, diffHUM)) {
  510. humValue = newHumValue;
  511. sendState();
  512. }
  513.  
  514.  
  515. int newLDR = analogRead(LDRPIN);
  516.  
  517. if (checkBoundSensor(newLDR, LDR, diffLDR)) {
  518. LDR = newLDR;
  519. sendState();
  520. }
  521.  
  522. }
  523.  
  524. if (flash) {
  525. if (startFlash) {
  526. startFlash = false;
  527. flashStartTime = millis();
  528. }
  529.  
  530. if ((millis() - flashStartTime) <= flashLength) {
  531. if ((millis() - flashStartTime) % 1000 <= 500) {
  532. setColor(flashRed, flashGreen, flashBlue);
  533. }
  534. else {
  535. setColor(0, 0, 0);
  536. // If you'd prefer the flashing to happen "on top of"
  537. // the current color, uncomment the next line.
  538. // setColor(realRed, realGreen, realBlue);
  539. }
  540. }
  541. else {
  542. flash = false;
  543. setColor(realRed, realGreen, realBlue);
  544. }
  545. }
  546.  
  547. if (startFade) {
  548. // If we don't want to fade, skip it.
  549. if (transitionTime == 0) {
  550. setColor(realRed, realGreen, realBlue);
  551.  
  552. redVal = realRed;
  553. grnVal = realGreen;
  554. bluVal = realBlue;
  555.  
  556. startFade = false;
  557. }
  558. else {
  559. loopCount = 0;
  560. stepR = calculateStep(redVal, realRed);
  561. stepG = calculateStep(grnVal, realGreen);
  562. stepB = calculateStep(bluVal, realBlue);
  563.  
  564. inFade = true;
  565. }
  566. }
  567.  
  568. if (inFade) {
  569. startFade = false;
  570. unsigned long now = millis();
  571. if (now - lastLoop > transitionTime) {
  572. if (loopCount <= 1020) {
  573. lastLoop = now;
  574.  
  575. redVal = calculateVal(stepR, redVal, loopCount);
  576. grnVal = calculateVal(stepG, grnVal, loopCount);
  577. bluVal = calculateVal(stepB, bluVal, loopCount);
  578.  
  579. setColor(redVal, grnVal, bluVal); // Write current values to LED pins
  580.  
  581. Serial.print("Loop count: ");
  582. Serial.println(loopCount);
  583. loopCount++;
  584. }
  585. else {
  586. inFade = false;
  587. }
  588. }
  589. }
  590. }
  591.  
  592. /**************************** START TRANSITION FADER *****************************************/
  593. // From https://www.arduino.cc/en/Tutorial/ColorCrossfader
  594. /* BELOW THIS LINE IS THE MATH -- YOU SHOULDN'T NEED TO CHANGE THIS FOR THE BASICS
  595.  
  596. The program works like this:
  597. Imagine a crossfade that moves the red LED from 0-10,
  598. the green from 0-5, and the blue from 10 to 7, in
  599. ten steps.
  600. We'd want to count the 10 steps and increase or
  601. decrease color values in evenly stepped increments.
  602. Imagine a + indicates raising a value by 1, and a -
  603. equals lowering it. Our 10 step fade would look like:
  604.  
  605. 1 2 3 4 5 6 7 8 9 10
  606. R + + + + + + + + + +
  607. G + + + + +
  608. B - - -
  609.  
  610. The red rises from 0 to 10 in ten steps, the green from
  611. 0-5 in 5 steps, and the blue falls from 10 to 7 in three steps.
  612.  
  613. In the real program, the color percentages are converted to
  614. 0-255 values, and there are 1020 steps (255*4).
  615.  
  616. To figure out how big a step there should be between one up- or
  617. down-tick of one of the LED values, we call calculateStep(),
  618. which calculates the absolute gap between the start and end values,
  619. and then divides that gap by 1020 to determine the size of the step
  620. between adjustments in the value.
  621. */
  622. int calculateStep(int prevValue, int endValue) {
  623. int step = endValue - prevValue; // What's the overall gap?
  624. if (step) { // If its non-zero,
  625. step = 1020 / step; // divide by 1020
  626. }
  627.  
  628. return step;
  629. }
  630.  
  631. /* The next function is calculateVal. When the loop value, i,
  632. reaches the step size appropriate for one of the
  633. colors, it increases or decreases the value of that color by 1.
  634. (R, G, and B are each calculated separately.)
  635. */
  636. int calculateVal(int step, int val, int i) {
  637. if ((step) && i % step == 0) { // If step is non-zero and its time to change a value,
  638. if (step > 0) { // increment the value if step is positive...
  639. val += 1;
  640. }
  641. else if (step < 0) { // ...or decrement it if step is negative
  642. val -= 1;
  643. }
  644. }
  645.  
  646. // Defensive driving: make sure val stays in the range 0-255
  647. if (val > 255) {
  648. val = 255;
  649. }
  650. else if (val < 0) {
  651. val = 0;
  652. }
  653.  
  654. return val;
  655. }
  656.  
  657. /****reset***/
  658. void software_Reset() // Restarts program from beginning but does not reset the peripherals and registers
  659. {
  660. Serial.print("resetting");
  661. ESP.reset();
  662. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement