Advertisement
Guest User

Untitled

a guest
Jan 27th, 2018
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.19 KB | None | 0 0
  1. #include <ESPMetRED.h>
  2.  
  3. const char* MQTT_PUBLISH_TOPIC = "ESPBATTBUTTON/OUT";
  4. const char* MQTT_SUBSCRIBE_TOPIC = "ESPBATTBUTTON/IN";
  5. const char* CLIENT_ID = "ESPBATTBUTTON";
  6. const char* WIFI_SSID = "Ahmed";
  7. const char* WIFI_PASSWORD = "WiFI Password";
  8. const char* MQTT_SERVER = "192.168.50.30";
  9. const char* MQTT_USER = "pi";
  10. const char* MQTT_PASSWORD = "MQTT Password";
  11.  
  12. IPAddress ip(192, 168, 50, 40);
  13. IPAddress gateway(192, 168, 50, 1);
  14. IPAddress subnet(255, 255, 255, 0);
  15. IPAddress dns(192, 168, 50, 1);
  16.  
  17. ESPMetRED client(ip, gateway, subnet, dns); //starting library with fixed IP
  18.  
  19. int buttons[2] = {4, 5}; // Pins on which buttons are attached
  20. int button;              // Variable to store the button which triggered the bootup
  21. int wake = 12;           // Pin which is used to Keep ESP awake until job is finished
  22.  
  23. boolean published = false;
  24. boolean notified = false;
  25.  
  26. void setup() {
  27.  
  28. // ESP Awake Pin, the pin which keeps CH_PD HIGH, a requirement for normal functioning of ESP8266
  29.   pinMode(wake, OUTPUT);
  30.   digitalWrite(wake, HIGH);
  31.  
  32.  
  33. //Check which button was pressed
  34.  
  35.   for(int i=0; i<4; i++)
  36.   {
  37.     pinMode(buttons[i], INPUT);
  38.     if(digitalRead(buttons[i]) == HIGH)
  39.     {
  40.       button = buttons[i];
  41.       return; //Push Button identified, Leave the loop
  42.     }
  43.   }
  44. }
  45.  
  46. void loop() {
  47.   client.keepalive(); // Necessary for successful connection between server and client
  48.  
  49.   if((client.stMqTT()) && (!published)) // stMqTT() function returns the MQTT connection state
  50.   {
  51.     published = true;
  52.     client.Publish("debug", client.JsonString(String(CLIENT_ID), String(button))); //Publish the data about Pushed Button
  53.   }
  54.  
  55.   if((published) && (digitalRead(button) == HIGH)) // Check if button is released, a debounce step
  56.   {
  57.     if(!notified) // Notify the server that Button is not yet released
  58.     {
  59.       notified = true;
  60.       client.Publish("debug", String(CLIENT_ID) + " [ESP Waiting Release of Button]");
  61.     }
  62.   }
  63.   else if((published) && (digitalRead(button) == LOW)) //Push Button has released, Let's get switched OFF
  64.   {
  65.     client.Publish("debug", String(CLIENT_ID) + " [ESP's Going DOWN]");
  66.     digitalWrite(wake, LOW); //Turns the ESP OFF
  67.   }
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement