#include <DHT.h> // Include DHT library
#define DHTPIN 4 // Define the pin for DHT sensor data
#define DHTTYPE DHT22 // Define the type of DHT sensor you're using
// Define ultrasonic sensor pins
#define TRIGGER_PIN 2
#define ECHO_PIN 3
// Define LDR sensor pin
#define LDR_PIN A0
// Define LED pin
#define LED_PIN 13
// Initialize DHT sensor
DHT dht(DHTPIN, DHTTYPE);
// Function to read LDR sensor
int readLDR() {
return analogRead(LDR_PIN);
}
// Function to read ultrasonic sensor
long readUltrasonic() {
long duration;
digitalWrite(TRIGGER_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIGGER_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIGGER_PIN, LOW);
duration = pulseIn(ECHO_PIN, HIGH);
return (duration / 2) / 29.1; // Calculate distance in centimeters
}
// Function to read temperature and humidity using DHT sensor
void readTempHumidity(float& temperature, float& humidity) {
humidity = dht.readHumidity();
temperature = dht.readTemperature();
}
void setup() {
// Start serial communication
Serial.begin(9600);
// Initialize the DHT sensor
dht.begin();
// Set LED pin as output
pinMode(LED_PIN, OUTPUT);
}
void loop() {
// Define array
int sensorArray[] = {1, 2, 3};
for (int i = 0; i < 3; i++) {
int sensor = sensorArray[i];
if (sensor == 1) {
// Read LDR sensor
int ldrValue = readLDR();
if (ldrValue < 500) { // Assuming "low intensity" means a value below 500
digitalWrite(LED_PIN, HIGH); // Turn on LED
} else {
digitalWrite(LED_PIN, LOW); // Turn off LED
}
Serial.print("Reading LDR sensor: ");
Serial.println(ldrValue); // Print LDR value
}
if (sensor == 2) {
// Read ultrasonic sensor
long distance = readUltrasonic();
// Check if object is closer than 20 cm
if (distance < 20) {
digitalWrite(LED_PIN, HIGH); // Turn on LED
} else {
digitalWrite(LED_PIN, LOW); // Turn off LED
}
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
}
if (sensor == 3) {
// Read temperature and humidity using DHT sensor
float humidity, temperature;
readTempHumidity(temperature, humidity);
// Check if readings are valid
if (isnan(humidity) || isnan(temperature)) {
Serial.println("Failed to read from DHT sensor!");
} else {
Serial.print("Humidity: ");
Serial.print(humidity);
Serial.print("%, Temperature: ");
Serial.print(temperature);
Serial.println("°C");
}
}
// Wait a short delay between measurements
delay(1000);
}
}