Advertisement
Guest User

Untitled

a guest
Feb 15th, 2018
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.96 KB | None | 0 0
  1.  #include <ESP8266WiFi.h>
  2. #include <WiFiClient.h>
  3. #include <ESP8266WebServer.h>
  4. #include <ESP8266mDNS.h>
  5. #include <WiFiUdp.h>
  6. #include <PubSubClient.h>
  7.  
  8. //Your MQTT Broker
  9. const char* mqtt_server = "xxx";
  10. const char* mqtt_user = "xxx";
  11. const char* mqtt_passwd = "xxx";
  12. const char* mqtt_topic = "Bewegung_01";
  13. const char* mqtt_ClientID = "Bewegung01";
  14.  
  15. //Your Wifi SSID
  16. const char* ssid = "xxx";
  17. //Your Wifi Key
  18. const char* password = "xxx";
  19.  
  20. ESP8266WebServer server(80);
  21.  
  22. WiFiClient espClient;
  23. PubSubClient client(espClient);
  24.  
  25. int Input3 = 3; //the RX pin is the input!!!
  26. int sensorValue3 = 0, oldValue3 = 0, tmp = 10, val = 0;
  27. char msg[40];
  28.  
  29. void setup(void)
  30. {
  31. Serial.begin(115200);
  32. Serial.println("");
  33. //connect to WIFI
  34. WiFi.persistent(false);
  35. WiFi.mode(WIFI_OFF);
  36. WiFi.mode(WIFI_STA);
  37. WiFi.begin(ssid, password);
  38.  
  39. // Wait for WiFi
  40. Serial.println("");
  41. Serial.print("Connecting to: ");
  42. Serial.println(ssid);
  43. while (WiFi.status() != WL_CONNECTED)
  44. {
  45. delay(500);
  46. Serial.print(".");
  47. if(tmp)
  48. {
  49. tmp--;
  50. }
  51. else
  52. {
  53. snprintf (msg, 40,"No connection to %s: ", ssid, " -> break");
  54. Serial.println(msg);
  55. break;
  56. }
  57. }
  58. tmp = 10;
  59. Serial.println("");
  60. Serial.print("IP-Adress: ");
  61. Serial.println(WiFi.localIP());
  62. //connect to mqtt broker
  63. client.setServer(mqtt_server, 1883);
  64.  
  65. while (!client.connected())
  66. {
  67. if (client.connect(mqtt_ClientID, mqtt_user, mqtt_passwd))
  68. {
  69. client.subscribe(mqtt_topic);
  70. }
  71. else
  72. {
  73. if(tmp)
  74. {
  75. Serial.print("*");
  76. tmp--;
  77. }
  78. else
  79. {
  80. Serial.println("No connection to broker -> break");
  81. break;
  82. }
  83. }
  84. }
  85.  
  86. Serial.println("switching to motion dectector...");
  87. delay(100);
  88. pinMode(Input3, INPUT);
  89. pinMode(2, OUTPUT);
  90. }
  91.  
  92. void loop(void){
  93. sensorValue3 = digitalRead(Input3);
  94. if(sensorValue3 != oldValue3)
  95. {
  96. oldValue3 = sensorValue3;
  97. if(tmp)
  98. {
  99. snprintf (msg, 40, "%s: %s", mqtt_ClientID, (sensorValue3 == 0) ? "0" : "1");
  100. client.publish(mqtt_topic, msg);
  101. }
  102. else
  103. {
  104. digitalWrite(2,sensorValue3);
  105. }
  106. }
  107. delay(100);
  108. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement