Guest User

Untitled

a guest
Oct 9th, 2018
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.07 KB | None | 0 0
  1. #include <ESP8266WiFi.h>
  2. #include <PubSubClient.h>
  3.  
  4. // WiFi credentials
  5. char ssid[] = "";
  6. char pass[] = "";
  7.  
  8. // MQTT broker details
  9. const char* server = "";
  10. const char* username = "notabot";
  11. const char* password = "";
  12.  
  13. // Change as required
  14. const char* topic = "Home/mailbox";
  15. const char* msg = "You Got Mail!";
  16. byte QoS = 2;
  17. boolean retain = false;
  18.  
  19. WiFiClient espClient;
  20. PubSubClient mqttClient(espClient);
  21.  
  22. void youGotMail() {
  23. Serial.println("You got mail!");
  24. while (!mqttClient.connected()) {
  25. Serial.print("Attempting MQTT connection...");
  26. // Attempt to connect
  27. if (mqttClient.connect("espbot", username, password, topic, QoS, retain, msg)) {
  28. Serial.println("connected");
  29. // Once connected, publish an announcement...
  30. if ( mqttClient.publish(topic, msg)) {
  31. Serial.println("Successfully published.");
  32. }
  33. } else {
  34. Serial.print("failed, rc=");
  35. Serial.print(mqttClient.state());
  36. Serial.println(" try again in 5 seconds");
  37. // Wait 5 seconds before retrying
  38. delay(5000);
  39. }
  40. }
  41. }
  42. void setup() {
  43. Serial.begin(115200);
  44. while (!Serial) {}
  45. Serial.print("Reading sensor: ");
  46. Serial.println(analogRead(A0));
  47. if (analogRead(A0) > 500) {
  48. // Connect to WiFi
  49. WiFi.begin(ssid, pass);
  50. while (WiFi.status() != WL_CONNECTED) {
  51. delay(500);
  52. Serial.print(".");
  53. }
  54. if (WL_CONNECTED) {
  55. Serial.println("Connected!");
  56. }
  57.  
  58. pinMode(A0, INPUT);
  59. Serial.print("Reading sensor: ");
  60. Serial.println(analogRead(A0));
  61. mqttClient.setServer(server, 1883);
  62. // Run our notification logic
  63. youGotMail();
  64. mqttClient.disconnect();
  65. // I found that not disconnecting caused issues with my router...
  66. WiFi.disconnect(true);
  67. }
  68. // Sleep for 60 seconds
  69. ESP.deepSleep(60*1000000);
  70. }
  71.  
  72. // The void loop is never reached when using deepSleep()
  73. // All code must be executed in the setup() function.
  74. void loop() {
  75. }
Add Comment
Please, Sign In to add comment