Advertisement
merkelck

remote

Feb 17th, 2019
161
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.00 KB | None | 0 0
  1.  
  2. #include <ESP8266WiFi.h>
  3. #include <PubSubClient.h>
  4.  
  5. const char* ssid = "xxx";
  6. const char* password = "xxxxxxx";
  7. const char* mqttServer = "192.168.1.xx";
  8. const int mqttPort = 1883;
  9.  
  10. #define LED 5 // D1(gpio5)
  11. #define BUTTON 4 //D2(gpio4)
  12. //Let's say you have your push button on pin 4
  13. int switchState = 0; // actual read value from pin4
  14. int oldSwitchState = 0; // last read value from pin4
  15. int lightsOn = 0; // is the switch on = 1 or off = 0
  16.  
  17. WiFiClient espClient;
  18. PubSubClient client(espClient);
  19.  
  20. void setup() {
  21.  
  22. Serial.begin(115200);
  23. WiFi.begin(ssid, password);
  24. while (WiFi.status() != WL_CONNECTED) {
  25. delay(500);
  26. Serial.println("Connecting to WiFi..");
  27. Serial.print("Connected to ");
  28. Serial.print(ssid);
  29. Serial.println();
  30. }
  31.  
  32.  
  33. client.setServer(mqttServer, mqttPort);
  34. // client.setCallback(callback);
  35.  
  36. while (!client.connected()) {
  37. Serial.println("Connecting to MQTT...");
  38.  
  39. if (client.connect("ESP8266Client" )) {
  40.  
  41. Serial.print("connected");
  42.  
  43. } else {
  44.  
  45. Serial.print("failed with state ");
  46. Serial.print(client.state());
  47. delay(2000);
  48.  
  49. }
  50. }
  51.  
  52. client.publish("home/office/sonoff1", "Remote");
  53. client.subscribe("home/office/sonoff1");
  54.  
  55.  
  56. pinMode(BUTTON, INPUT); // push button
  57. pinMode(LED, OUTPUT); // anything you want to control using a switch e.g. a Led
  58. }
  59. void loop ()
  60. {
  61. switchState = digitalRead(BUTTON); // read the pushButton State
  62. if (switchState != oldSwitchState) // catch change
  63. {
  64. oldSwitchState = switchState;
  65. if (switchState == HIGH)
  66. {
  67. // toggle
  68. lightsOn = !lightsOn;
  69. }
  70.  
  71. if(lightsOn)
  72. {
  73. digitalWrite(LED, HIGH); // set the LED on
  74. client.publish("home/office/sonoff1", "on");
  75. }
  76. else
  77. {
  78. digitalWrite(LED, LOW); // set the LED off
  79. client.publish("home/office/sonoff1", "off");
  80. }
  81. }
  82.  
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement