Advertisement
hanpa

Wemos D1 mini to send MQTT messages when motion is detected

Jun 10th, 2017
244
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 5.02 KB | None | 0 0
  1. Using Wemos D1 mini to send MQTT messages when motion is detected through connected HF sensor.
  2. The HF sensor has 230V output that is transformed to 3.3V using a small 230V to 3.3V power supply.
  3.  
  4. http://www.hobbyelektronik.nu/forum/viewtopic.php?f=13&t=37
  5.  
  6. #include <ESP8266WiFi.h>
  7. #include <ESP8266mDNS.h>
  8. #include <WiFiUdp.h>
  9. #include <ArduinoOTA.h>
  10. #include <PubSubClient.h>
  11.  
  12. const char* version = "HF_motion_mqtt 1.0";
  13. const char* date_name = "2017-06-10 Hans Palm";
  14.  
  15. // Code for using Wemos D1 Mini with a HF motion detector
  16. // 3.3V input on D1 when sensor is trigged
  17. // MQTT messages according to outTopic* are sent when D1 input becomes active = high
  18. // D1 must become low before new activation can occur
  19.  
  20. // When activated, MQTT messages similar to the following are sent:
  21. // Activates kitchen timer:
  22. //
  23. //   mosquitto_pub -h localhost -t "KTActivate" -m "1"
  24. //
  25. // Activates Ikea TrΓ₯dfri lamp above kitchen table
  26. //
  27. // mosquitto_pub -h localhost -t "tradfri_kbordet" -m "1"
  28.  
  29. // Wifi settings
  30. const char* ssid = "SSID";
  31. const char* password = "password";
  32. const char* host = "OTAHOSTNAME";
  33.  
  34. // The follwing parameters are only required for fixed IP, otherwise uncomment, also uncomment WiFi.config(ip, gateway, subnet)
  35. IPAddress ip(192, 168, 0, 170);
  36. IPAddress gateway(192, 168, 0, 1);
  37. IPAddress subnet(255, 255, 255, 0);
  38.  
  39. // MQTT server and topic settings
  40. const char* mqtt_server = "192.168.0.xxx";
  41. const char* clientID = "MotionKitchenOTA";
  42. const char* outTopic_KTActivate = "KTActivate";        
  43. const char* outTopic_tradfri_kbordet = "tradfri_kbordet";
  44.  
  45. const char* inTopic = "TBD"; // Not used in this sketch
  46.  
  47. bool trigged = false;
  48.  
  49. WiFiClient espClient;
  50. PubSubClient client(espClient);
  51.  
  52. void setup()
  53. {
  54.   Serial.begin(115200);
  55.   delay(10);
  56.   Serial.println("setup started ");
  57.  
  58.   pinMode(LED_BUILTIN, OUTPUT);
  59.   pinMode(D1, INPUT);
  60.  
  61.   // Connect to WiFi network
  62.   WiFi.config(ip, gateway, subnet); // Only required for fixed IP
  63.   WiFi.begin(ssid, password);
  64.  
  65.   while (WiFi.status() != WL_CONNECTED) {
  66.     delay(500);
  67.     Serial.print(".");
  68.   }
  69.  
  70.  
  71.  ArduinoOTA.setHostname(host);    
  72.  ArduinoOTA.onStart([]() {
  73.     String type;
  74.     type = "sketch";
  75.     Serial.println("Start updating " + type);
  76.   });
  77.   ArduinoOTA.onEnd([]() {
  78.     Serial.println("\nEnd");
  79.   });
  80.   ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
  81.     Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
  82.   });
  83.   ArduinoOTA.onError([](ota_error_t error) {
  84.     Serial.printf("Error[%u]: ", error);
  85.     if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed");
  86.     else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed");
  87.     else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed");
  88.     else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed");
  89.     else if (error == OTA_END_ERROR) Serial.println("End Failed");
  90.   });
  91.   ArduinoOTA.begin();
  92.  
  93.   Serial.println("");
  94.   Serial.println("WiFi connected");
  95.   Serial.println("IP address: ");
  96.   Serial.println(WiFi.localIP());
  97.   client.setServer(mqtt_server, 1883);
  98.   client.setCallback(callback);
  99. }
  100.  
  101. void callback(char* topic, byte* payload, unsigned int length) {
  102.   // Check incoming message using really ugly code
  103.   String nstring = "";
  104.   Serial.print("Message arrived [");
  105.   Serial.print(topic);
  106.   Serial.print("] ");
  107.   for (int i = 0; i < length; i++) {
  108.     Serial.print((char)payload[i]);
  109.     nstring = String (nstring + (char)payload[i]);
  110.   }
  111.   nstring = String (nstring + '\0');
  112.   Serial.println("");
  113.   Serial.print("nstring = ");
  114.   Serial.println(nstring);
  115.   int value;
  116.   if (String(topic + '\0' == inTopic)) {
  117.     value = nstring.toInt(); // (long) 0 is returned if unsuccessful)
  118.     if (value > 0 ) {
  119.       // Serial.print("TBD value change to ");
  120.       Serial.print(value);
  121.       Serial.println(" requested");
  122.       // TBD
  123.     }
  124.   }
  125. }
  126.  
  127. void reconnect() {
  128.   // Loop until we're reconnected
  129.   while (!client.connected()) {
  130.     Serial.print("Attempting MQTT connection...");
  131.     // Attempt to connect
  132.     if (client.connect(clientID)) {
  133.       Serial.println("connected");
  134.       // Once connected, publish an announcement...
  135.       // ... and resubscribe
  136.       client.subscribe(inTopic);
  137.     } else {
  138.       Serial.print("failed, rc=");
  139.       Serial.print(client.state());
  140.       Serial.println(" try again in 5 seconds");
  141.       // Wait 5 seconds before retrying
  142.       delay(5000);
  143.     }
  144.   }
  145. }
  146.  
  147. void loop()
  148. {
  149.   ArduinoOTA.handle();
  150.  
  151.   // Check if a client has connected
  152.   if (!client.connected()) {
  153.     reconnect();
  154.   }
  155.  
  156.   // Perform PubSubClient tasks
  157.   client.loop();
  158.  
  159.   int input = digitalRead(D1);
  160.   digitalWrite(LED_BUILTIN, !input);
  161.  
  162.   if (input) {
  163.     if (!trigged) {
  164.       trigged = true;
  165.       char msg[50];
  166.       snprintf (msg, 75, "1");
  167.       client.publish(outTopic_tradfri_kbordet, msg);
  168.       snprintf (msg, 75, "1");
  169.       client.publish(outTopic_KTActivate, msg);
  170.     }
  171.   } else {
  172.     trigged = false;
  173.   }
  174.  
  175.   delay(10); // Probably not required
  176. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement