#include <DHT.h>
#define DHTPIN 2 // Pin where the DHT sensor is connected
#define DHTTYPE DHT22 // DHT 11 or DHT 12
// Replace DHTTYPE with DHT12 if you're using DHT12 sensor
DHT dht(DHTPIN, DHTTYPE);
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
Serial.println("DHTxx test! Done successfully by Sundram");
dht.begin();
}
void loop() {
// put your main code here, to run repeatedly:
delay(2000); // Wait for 2 seconds between measurements
float humidity = dht.readHumidity();
float temperature = dht.readTemperature();
if (isnan(humidity) || isnan(temperature)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
}
/*Here's a breakdown of what this code does:
Import the DHT library.
Define the pin to which the DHT sensor is connected (DHTPIN) and the type of the sensor (DHTTYPE). Change DHTTYPE to DHT12 if you're using a DHT12 sensor.
Initialize the DHT sensor object.
In the setup() function, start serial communication and print a message to indicate that the DHT sensor is being tested.
In the loop() function, wait for 2 seconds.
Read humidity and temperature values from the sensor.
Check if the readings are valid.
If valid, print the humidity and temperature values to the Serial Monitor.
Make sure you have installed the DHT library in your Arduino IDE. You can do this by going to Sketch > Include Library > Manage Libraries, then search for "DHT" and install the library developed by Adafruit.*/