Advertisement
Guest User

Untitled

a guest
May 13th, 2017
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.22 KB | None | 0 0
  1. #include <ESP8266WiFi.h>
  2. #include <PubSubClient.h>
  3.  
  4. //WIFI
  5. const char* wifi_ssid = "wifi";
  6. const char* wifi_password = "wifi-password";
  7.  
  8. //MQTT
  9. const char* mqtt_server = "mqtt server ip";
  10. const char* mqtt_user = "mqtt username";
  11. const char* mqtt_password = "mqtt password";
  12. const char* clientID = "Doorbell";
  13.  
  14. //VARS
  15. const char* doorbell_topic = "home/outdoors/doorbell";
  16. const int doorbellPin = D3;
  17. int doorbellState = 0;
  18.  
  19. WiFiClient espClient;
  20. PubSubClient client(espClient);
  21.  
  22. void setup() {
  23. Serial.begin(115200);
  24. pinMode(doorbellPin, INPUT_PULLUP);
  25. pinMode(LED_BUILTIN, OUTPUT); // Initialize the LED_BUILTIN pin as an output
  26.  
  27. setup_wifi();
  28. client.setServer(mqtt_server, 1883);
  29. }
  30.  
  31. void blink_now(){
  32. digitalWrite(LED_BUILTIN, LOW);
  33. delay(1000);
  34. digitalWrite(LED_BUILTIN, HIGH);
  35. delay(1000);
  36. }
  37.  
  38. void setup_wifi() {
  39. //Turn off Access Point
  40. WiFi.mode(WIFI_STA);
  41. delay(10);
  42.  
  43. // We start by connecting to a WiFi network
  44. Serial.println();
  45. Serial.print("Connecting to ");
  46. Serial.println(wifi_ssid);
  47.  
  48. WiFi.begin(wifi_ssid, wifi_password);
  49.  
  50. while (WiFi.status() != WL_CONNECTED) {
  51. delay(500);
  52. Serial.print(".");
  53. blink_now();
  54. }
  55.  
  56. Serial.println("");
  57. Serial.println("WiFi connected");
  58. Serial.println("IP address: ");
  59. Serial.println(WiFi.localIP());
  60. }
  61.  
  62. void reconnect() {
  63. // Loop until we're reconnected
  64. while (!client.connected()) {
  65. Serial.print("Attempting MQTT connection...");
  66. blink_now();
  67. // Attempt to connect
  68. if (client.connect(clientID, mqtt_user, mqtt_password)) {
  69. Serial.println("connected");
  70. // Once connected, publish an announcement...
  71. client.publish(doorbell_topic, "Doorbell connected to MQTT");
  72. } else {
  73. Serial.print("failed, rc=");
  74. Serial.print(client.state());
  75. Serial.println(" try again in 5 seconds");
  76. // Wait 5 seconds before retrying
  77. delay(5000);
  78. }
  79. }
  80. }
  81.  
  82. void loop() {
  83. if (!client.connected()) {
  84. reconnect();
  85. }
  86. client.loop();
  87. doorbellState = digitalRead(doorbellPin);
  88.  
  89. if ( doorbellState == LOW ) {
  90. // Put your code here. e.g. connect, send, disconnect.
  91. Serial.println("Doorbell is pressed!");
  92. client.publish(doorbell_topic, "on", true);
  93. blink_now();
  94.  
  95. delay( 5000 );
  96. }
  97. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement