#include <DHT.h> // Include the DHT library
#define DHTPIN 7 // Pin connected to DHT11 Data
#define DHTTYPE DHT11 // Define the DHT sensor type
#define BUTTON_PIN 2 // Pin connected to Push Button
#define LED_PIN 13
DHT dht(DHTPIN, DHTTYPE); // Initialize DHT sensor
void setup() {
Serial.begin(9600); // Start serial communication for displaying data on Serial Monitor
pinMode(BUTTON_PIN, INPUT); // Set button pin as input
dht.begin(); // Initialize the DHT sensor
}
void loop() {
int buttonState = digitalRead(BUTTON_PIN); // Read the state of the button
if (buttonState == HIGH) {
digitalWrite(LED_PIN, HIGH); // Turn on the LED when button is pressed
} else {
digitalWrite(LED_PIN, LOW); // Turn off the LED when button is not pressed
}
// Read temperature and humidity from the DHT11 sensor
float humidity = dht.readHumidity();
float temperature = dht.readTemperature();
// Check if the sensor readings are valid
if (isnan(humidity) || isnan(temperature)) {
Serial.println("Failed to read from DHT sensor!");
} else {
// Print the temperature and humidity to the Serial Monitor
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.print(" °C\t");
Serial.print("Humidity: ");
Serial.print(humidity);
Serial.println(" %");
}
delay(2000); // Wait 2 seconds before the next loop iteration
}