#include <DHT.h>
#define DHTPIN 25 // Digital pin connected to the DHT sensor
#define DHTTYPE DHT22 // Type of the DHT sensor (DHT11, DHT22)
#define BUTTON_PIN 12
#define LED_PIN 13 // Change to a different pin for LED
DHT dht(DHTPIN, DHTTYPE); // Initialize DHT sensor
bool previousButtonState = HIGH; // Variable to store the previous state of the button
void button(bool pressed) {
float humidity = dht.readHumidity();
float temperature = dht.readTemperature(); // Read temperature in Celsius
// Check if any reads failed and exit early (to try again).
if (isnan(humidity) || isnan(temperature)) {
Serial.println(F("Failed to read from DHT sensor!"));
return;
}
if (pressed) {
digitalWrite(LED_PIN, HIGH);
Serial.print(F("Temperature: "));
Serial.println(temperature);
} else {
digitalWrite(LED_PIN, LOW);
Serial.print(F("Humidity: "));
Serial.println(humidity);
}
}
void setup() {
Serial.begin(115200);
dht.begin(); // Initialize DHT sensor
pinMode(BUTTON_PIN, INPUT_PULLUP);
pinMode(LED_PIN, OUTPUT);
}
void loop() {
delay(50); // Add a small delay to debounce the button
// Read the current state of the button
bool currentButtonState = digitalRead(BUTTON_PIN);
// Check if the button state has changed
if (currentButtonState != previousButtonState) {
// Execute instructions only once when the button value changes
button(currentButtonState == LOW); // Pass true if button is pressed, false otherwise
}
// Update the previous button state
previousButtonState = currentButtonState;
}