From 51a7c2adc53cbb88022b974eebfa3e479c810bd1 Mon Sep 17 00:00:00 2001 From: Caleb Mah Date: Thu, 16 Jul 2020 23:32:23 +0800 Subject: [PATCH] PIR sensor usermod --- usermods/PIR_sensor_mqtt_v1/README.md | 9 +++++ usermods/PIR_sensor_mqtt_v1/usermod.cpp | 53 +++++++++++++++++++++++++ 2 files changed, 62 insertions(+) create mode 100644 usermods/PIR_sensor_mqtt_v1/README.md create mode 100644 usermods/PIR_sensor_mqtt_v1/usermod.cpp diff --git a/usermods/PIR_sensor_mqtt_v1/README.md b/usermods/PIR_sensor_mqtt_v1/README.md new file mode 100644 index 00000000..475c11b0 --- /dev/null +++ b/usermods/PIR_sensor_mqtt_v1/README.md @@ -0,0 +1,9 @@ +# PIR sensor with MQTT + +This simple usermod allows attaching a PIR sensor like the AM312 and publish the readings over MQTT. A message is sent when motion is detected as well as when motion has stopped. + +This usermod has only been tested with the AM312 sensor though should work for any other PIR sensor. Note that this does not control the LED strip directly, it only publishes MQTT readings for use with other integrations like Home Assistant. + +## Installation + +Copy and replace the file `usermod.cpp` in wled00 directory. diff --git a/usermods/PIR_sensor_mqtt_v1/usermod.cpp b/usermods/PIR_sensor_mqtt_v1/usermod.cpp new file mode 100644 index 00000000..117b7c71 --- /dev/null +++ b/usermods/PIR_sensor_mqtt_v1/usermod.cpp @@ -0,0 +1,53 @@ +#include "wled.h" +/* + * This v1 usermod file allows you to add own functionality to WLED more easily + * See: https://github.com/Aircoookie/WLED/wiki/Add-own-functionality + * EEPROM bytes 2750+ are reserved for your custom use case. (if you extend #define EEPSIZE in const.h) + * If you just need 8 bytes, use 2551-2559 (you do not need to increase EEPSIZE) + * + * Consider the v2 usermod API if you need a more advanced feature set! + */ + +//Use userVar0 and userVar1 (API calls &U0=,&U1=, uint16_t) + +// PIR sensor pin +const int MOTION_PIN = 16; + +int prevState = LOW; + +//gets called once at boot. Do all initialization that doesn't depend on network here +void userSetup() +{ + pinMode(MOTION_PIN, INPUT); +} + +//gets called every time WiFi is (re-)connected. Initialize own network interfaces here +void userConnected() +{ + +} + +void publishMqtt(String state) +{ + //Check if MQTT Connected, otherwise it will crash the 8266 + if (mqtt != nullptr){ + char subuf[38]; + strcpy(subuf, mqttDeviceTopic); + strcat(subuf, "/kitchen_motion"); + mqtt->publish(subuf, 0, true, state.c_str()); + } +} + +//loop. You can use "if (WLED_CONNECTED)" to check for successful connection +void userLoop() +{ + if (digitalRead(MOTION_PIN) == HIGH && prevState == LOW) { // Motion detected + publishMqtt("ON"); + prevState = HIGH; + } + if (digitalRead(MOTION_PIN) == LOW && prevState == HIGH) { // Motion stopped + publishMqtt("OFF"); + prevState = LOW; + } +} +