Advertisement
merkelck

Untitled

Jul 12th, 2020
253
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.16 KB | None | 0 0
  1. /*********
  2. Rui Santos
  3. Complete project details at https://randomnerdtutorials.com
  4. NodeRED_ESP8266_ Multisensor Project code
  5. This code has been modified to ustilize only the motion sensor and use
  6. an esp8266-01
  7. *********/
  8.  
  9. // Load libraries
  10. #include <ESP8266WiFi.h>
  11. #include <PubSubClient.h>
  12. //#include <OneWire.h>
  13. //#include <DallasTemperature.h>
  14.  
  15. // Replace with your network credentials
  16. const char* ssid = "xxxxx";
  17. const char* password = "xx";
  18.  
  19. // Change the variable to your Raspberry Pi IP address, so it connects to your MQTT broker
  20. const char* mqtt_server = "192.168.1.xxx";
  21. // MQTT Broker IP example
  22. //const char* mqtt_server = "192.168.1.144";
  23.  
  24. // Initializes the espClient. You should change the espClient name if you have multiple ESPs running in your home automation system
  25. WiFiClient espClient;
  26. PubSubClient client(espClient);
  27.  
  28. // Variable to hold the temperature reading
  29. // String temperatureString = "";
  30.  
  31. // Set GPIOs for: output variable, status LED, PIR Motion Sensor, and LDR
  32. // const int output = 15;
  33. // const int statusLed = 12;
  34. const int motionSensor = 2;
  35. // const int ldr = A0;
  36. // Store the current output state
  37. // String outputState = "off";
  38.  
  39. // GPIO where the DS18B20 is connected to
  40. // const int oneWireBus = 4;
  41. // Setup a oneWire instance to communicate with any OneWire devices
  42. // OneWire oneWire(oneWireBus);
  43. // Pass our oneWire reference to Dallas Temperature sensor
  44. // DallasTemperature sensors(&oneWire);
  45.  
  46. // Timers - Auxiliary variables
  47. unsigned long now = millis();
  48. unsigned long lastMeasure = 0;
  49. boolean startTimer = false;
  50. unsigned long currentTime = millis();
  51. unsigned long previousTime = 0;
  52.  
  53. // Don't change the function below.
  54. // This function connects your ESP8266 to your router
  55. void setup_wifi() {
  56. delay(10);
  57. // We start by connecting to a WiFi network
  58. Serial.println();
  59. Serial.print("Connecting to ");
  60. Serial.println(ssid);
  61. WiFi.begin(ssid, password);
  62. while (WiFi.status() != WL_CONNECTED) {
  63. delay(500);
  64. Serial.print(".");
  65. }
  66. Serial.println("");
  67. Serial.print("WiFi connected - ESP IP address: ");
  68. Serial.println(WiFi.localIP());
  69. }
  70.  
  71. // This functions is executed when some device publishes a message to a topic that your ESP8266 is subscribed to
  72. // Change the function below to add logic to your program, so when a device publishes a message to a topic that
  73. // your ESP8266 is subscribed you can actually do something
  74. void callback(String topic, byte* message, unsigned int length) {
  75. Serial.print("Message arrived on topic: ");
  76. Serial.print(topic);
  77. Serial.print(". Message: ");
  78. String messageTemp;
  79.  
  80. for (int i = 0; i < length; i++) {
  81. Serial.print((char)message[i]);
  82. messageTemp += (char)message[i];
  83. }
  84. Serial.println();
  85. /*
  86. // Feel free to add more if statements to control more GPIOs with MQTT
  87. // If a message is received on the topic esp8266/output, you check if the message is either on or off.
  88. // Turns the output according to the message received
  89. if(topic=="esp8266/output"){
  90. Serial.print("Changing output to ");
  91. if(messageTemp == "on"){
  92. digitalWrite(output, LOW);
  93. Serial.print("on");
  94. }
  95. else if(messageTemp == "off"){
  96. digitalWrite(output, HIGH);
  97. Serial.print("off");
  98. }
  99. }
  100. */
  101. Serial.println();
  102. }
  103.  
  104. // This functions reconnects your ESP8266 to your MQTT broker
  105. // Change the function below if you want to subscribe to more topics with your ESP8266
  106. void reconnect() {
  107. // Loop until we're reconnected
  108. while (!client.connected()) {
  109. Serial.print("Attempting MQTT connection...");
  110. // Create a random client ID
  111. String clientId = "ESP8266Client-";
  112. clientId += String(random(0xffff), HEX);
  113. // Attempt to connect
  114. if (client.connect(clientId.c_str())) {
  115. Serial.println("connected");
  116. // Subscribe or resubscribe to a topic
  117. // You can subscribe to more topics (to control more outputs)
  118. client.subscribe("esp8266/output");
  119. } else {
  120. Serial.print("failed, rc=");
  121. Serial.print(client.state());
  122. Serial.println(" try again in 5 seconds");
  123. // Wait 5 seconds before retrying
  124. delay(5000);
  125. }
  126. }
  127. }
  128.  
  129. // Checks if motion was detected and the sensors are armed. Then, starts a timer.
  130. void detectsMovement() {
  131. Serial.println("MOTION DETECTED!");
  132. client.publish("esp8266/motion", "MOTION DETECTED!");
  133. previousTime = millis();
  134. startTimer = true;
  135. }
  136.  
  137. void setup() {
  138. // Start the DS18B20 sensor
  139. // sensors.begin();
  140.  
  141. // Serial port for debugging purposes
  142. Serial.begin(115200);
  143.  
  144. // PIR Motion Sensor mode, then set interrupt function and RISING mode
  145. pinMode(motionSensor, INPUT);
  146. attachInterrupt(digitalPinToInterrupt(motionSensor), detectsMovement, RISING);
  147.  
  148. // Initialize the output variable and the LED as OUTPUTs
  149. // pinMode(output, OUTPUT);
  150. // pinMode(statusLed, OUTPUT);
  151. // digitalWrite(output, HIGH);
  152. // digitalWrite(statusLed, LOW);
  153.  
  154. setup_wifi();
  155. client.setServer(mqtt_server, 1883);
  156. client.setCallback(callback);
  157. }
  158.  
  159. void loop() {
  160. if (!client.connected()) {
  161. reconnect();
  162. }
  163. client.loop();
  164.  
  165. // Timer variable with current time
  166. now = millis();
  167. /*
  168. // Publishes new temperature and LDR readings every 30 seconds
  169. if (now - lastMeasure > 30000) {
  170. lastMeasure = now;
  171. sensors.requestTemperatures();
  172. // Temperature in Celsius degrees
  173. temperatureString = String(sensors.getTempCByIndex(0));
  174. // Uncomment the next line for temperature in Fahrenheit degrees
  175. //temperatureString = String(sensors.getTempFByIndex(0));
  176. // Publishes Temperature values
  177. client.publish("esp8266/temperature", temperatureString.c_str());
  178. Serial.println("Temperature published");
  179.  
  180. // Publishes LDR values
  181. client.publish("esp8266/ldr", String(analogRead(ldr)).c_str());
  182. Serial.println("LDR values published");
  183. }
  184. */
  185. // After 10 seconds have passed since motion was detected, publishes a "No motion" message
  186. if ((now - previousTime > 10000) && startTimer) {
  187. client.publish("esp8266/motion", "No motion");
  188. Serial.println("Motion stopped");
  189. startTimer = false;
  190. }
  191. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement