#include <Arduino.h>
#include "DHTesp.h"
#define timeSeconds 3
// Set GPIOs for LED and PIR Motion Sensor
const int led = 33;
const int motionSensor = 32;
const int buzPin = 25;
const int pinDHT = 15;
int32_t contador = 0;
DHTesp dht;
// Timer: Auxiliary variables
unsigned long now = millis();
unsigned long lastTrigger = 0;
boolean startTimer = false;
boolean motion = false;
// Checks if motion was detected, sets LED HIGH and starts a timer
void IRAM_ATTR detectsMovement() {
digitalWrite(led, HIGH);
digitalWrite(buzPin, HIGH);
startTimer = true;
lastTrigger = millis();
}
void setup() {
// Serial port for debugging purposes
Serial.begin(115200);
// DHT Setup
dht.setup(pinDHT, DHTesp::DHT22);
// PIR Motion Sensor mode INPUT_PULLUP
pinMode(motionSensor, INPUT_PULLUP);
// Set motionSensor pin as interrupt, assign interrupt function and set RISING mode
attachInterrupt(digitalPinToInterrupt(motionSensor), detectsMovement, RISING);
// Set LED to LOW
pinMode(led, OUTPUT);
digitalWrite(led, LOW);
// Set Buzzer to LOW
pinMode(buzPin, OUTPUT);
digitalWrite(buzPin, LOW);
}
void loop() {
// Current time
now = millis();
if((digitalRead(led) == HIGH) && (motion == false)) {
contador++;
Serial.print(String(contador) + " ¡¡¡MOVIMIENTO DETECTADO!!! ");
motion = true;
}
// Turn off the LED after the number of seconds defined in the timeSeconds variable
if(startTimer && (now - lastTrigger > (timeSeconds*1000))) {
TempAndHumidity data = dht.getTempAndHumidity();
Serial.println("-> Alarma LED y zumbador detenido en " + String(timeSeconds*1000) + "[ms] ");
Serial.println(String(contador) + " Temperatura: " + String(data.temperature, 2) + "°C");
Serial.println(String(contador) + " Humedad: " + String(data.humidity, 1) + "%"); digitalWrite(led, LOW);
Serial.println("-----");
digitalWrite(buzPin, LOW);
startTimer = false;
motion = false;
}
delay(10);
}