#include <WiFi.h>
#include <ESP32Servo.h>
#include "DHT.h"
#define SECRET_SSID "Wokwi-GUEST"
#define SECRET_PASS ""
char ssid[] = SECRET_SSID; // your network SSID (name)
char pass[] = SECRET_PASS; // your network password
const int servoPin = 19;
Servo servo;
#define DHTTYPE DHT22
// DHT Sensor
uint8_t DHTPin = 4;
// Initialize DHT sensor.
DHT dht(DHTPin, DHTTYPE);
float Temperature;
float Humidity;
const int trigPin = 5;
const int echoPin = 18;
// Define sound speed in cm/uS
#define SOUND_SPEED 0.034
#define CM_TO_INCH 0.393701
long duration;
float distanceCm;
float distanceInch;
void setup() {
Serial.begin(115200);
Serial.println("Hello, ESP32!");
WiFi.mode(WIFI_STA);
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT);
servo.attach(servoPin, 500, 2400);
pinMode(DHTPin, INPUT);
dht.begin();
}
void loop() {
// Connect or reconnect to WiFi
if (WiFi.status() != WL_CONNECTED) {
Serial.print("Attempting to connect to SSID: ");
Serial.println(SECRET_SSID);
while (WiFi.status() != WL_CONNECTED) {
WiFi.begin(ssid, pass); // Connect to WPA/WPA2 network. Change this line if using open or WEP network
Serial.print(".");
delay(5000);
}
Serial.println("\nConnected.");
}
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculate the distance
distanceCm = duration * SOUND_SPEED / 2;
// Convert to inches
distanceInch = distanceCm * CM_TO_INCH;
int pos = 0;
if (distanceInch > 12) {
Serial.println("No presence detected");
delay(5000);
} else {
// Check temperature only when presence is detected
Temperature = dht.readTemperature(); // Gets the value of the temperature
if (Temperature > 38) {
Serial.println("High body temperature detected!");
Serial.print("Temperature: ");
Serial.print(Temperature);
Serial.println(" degrees Celsius");
// Add more actions here for the alert if needed
delay(15000);
} else {
Serial.println("Access Granted.");
Serial.println("Normal Body Temperature.");
for (pos = 0; pos <= 180; pos += 1) {
servo.write(pos);
delay(15);
}
for (pos = 180; pos >= 0; pos -= 1) {
servo.write(pos);
delay(15);
}
delay(5000);
}
}
}