#include <DHT.h>
#include <DHT_U.h>
// Set GPIOs for PIR Motion Sensor and DHT22
const int motionSensor = 13;
#define DHTPIN 14 // Pin yang terhubung dengan data DHT22
#define DHTTYPE DHT22 // DHT 22 (AM2302)
DHT dht(DHTPIN, DHTTYPE);
// Timer: Auxiliary variables
unsigned long now = millis();
unsigned long lastTrigger = 0;
boolean startTimer = false;
#define timeSeconds 5
// Checks if motion was detected, sets startTimer to true and sets the lastTrigger time
void IRAM_ATTR detectsMovement() {
Serial.println("MOTION DETECTED!!!");
startTimer = true;
lastTrigger = millis();
}
void setup() {
// Serial port for debugging purposes
Serial.begin(115200);
// 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);
// Inisialisasi DHT22
dht.begin();
}
void loop() {
// Current time
now = millis();
// Read data from DHT22
float h = dht.readHumidity();
float t = dht.readTemperature();
// Check if any reads failed and exit early (to try again).
if (isnan(h) || isnan(t)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
// Print sensor data to Serial Monitor
Serial.print("Suhu: ");
Serial.print(t);
Serial.print(" °C ");
Serial.print("Kelembaban: ");
Serial.print(h);
Serial.println(" %");
// Reset motion timer if motion is detected
if (startTimer && (now - lastTrigger > (timeSeconds * 1000))) {
Serial.println("Motion stopped...");
startTimer = false;
}
delay(2000); // Adjust the delay as necessary
}