First try version of the kitchen PIR
This commit is contained in:
36
src/main.cpp
36
src/main.cpp
@@ -8,7 +8,6 @@ const char* ssid = "JoNelsDarlings";
|
||||
const char* password = "Paris2016";
|
||||
const char* mqtt_server = "mqtt.ddns.kawomi.com";
|
||||
|
||||
|
||||
WiFiClient espClient;
|
||||
PubSubClient mqttClient(espClient);
|
||||
unsigned long lastMsg = 0;
|
||||
@@ -61,13 +60,16 @@ void reconnect() {
|
||||
}
|
||||
}
|
||||
|
||||
void send_mqtt(String value) {
|
||||
void send_mqtt(String status, long time_min=0) {
|
||||
const size_t CAPACITY = JSON_OBJECT_SIZE(1);
|
||||
StaticJsonDocument<CAPACITY> doc;
|
||||
|
||||
// create an object
|
||||
JsonObject object = doc.to<JsonObject>();
|
||||
object["status"] = value.c_str();
|
||||
object["status"] = status.c_str();
|
||||
if (time_min > 0) {
|
||||
object["minutes"] = time_min;
|
||||
}
|
||||
|
||||
// serialize the object and send the result to Serial
|
||||
static char sensorStatus[150];
|
||||
@@ -80,7 +82,7 @@ void send_mqtt(String value) {
|
||||
|
||||
void setup() {
|
||||
pinMode(LED_BUILTIN,OUTPUT);
|
||||
pinMode(PIR_PIN,INPUT);
|
||||
pinMode(PIR_PIN,INPUT_PULLUP);
|
||||
|
||||
Serial.begin(115200);
|
||||
setup_wifi();
|
||||
@@ -88,17 +90,31 @@ void setup() {
|
||||
|
||||
}
|
||||
|
||||
long previousMotionMillis=millis();
|
||||
short previousState=digitalRead(PIR_PIN);
|
||||
long previousNoMoNotifyMins=0;
|
||||
void loop() {
|
||||
if (!mqttClient.connected()) {
|
||||
reconnect();
|
||||
}
|
||||
mqttClient.loop();
|
||||
|
||||
int pir = digitalRead(PIR_PIN);
|
||||
if (pir == HIGH) {
|
||||
send_mqtt("motion");
|
||||
digitalWrite(LED_BUILTIN,HIGH);
|
||||
delay(1000);
|
||||
digitalWrite(LED_BUILTIN,LOW);
|
||||
short currentState = digitalRead(PIR_PIN);
|
||||
if (currentState != previousState) {
|
||||
if (currentState == HIGH) {
|
||||
send_mqtt("motion");
|
||||
digitalWrite(LED_BUILTIN,HIGH);
|
||||
delay(1000);
|
||||
digitalWrite(LED_BUILTIN,LOW);
|
||||
previousMotionMillis=millis();
|
||||
}
|
||||
previousState = currentState;
|
||||
}
|
||||
|
||||
long minsSinceLastMotion=(millis()-previousMotionMillis)/(1000*60);
|
||||
if (previousNoMoNotifyMins != minsSinceLastMotion) {
|
||||
send_mqtt("no_motion",minsSinceLastMotion);
|
||||
previousNoMoNotifyMins = minsSinceLastMotion;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user