#define DHTPIN 2 // Digital pin connected to the DHT sensor
#define DHTTYPE DHT22 // DHT 22 (AM2302)
unsigned long lastReadTime = 0;
byte data[5];
void setup() {
Serial.begin(9600);
pinMode(DHTPIN, INPUT_PULLUP);
Serial.println("DHT22 sensor setup");
}
void loop() {
unsigned long currentTime = millis();
if (currentTime - lastReadTime >= 2000) { // Wait at least 2 seconds between readings
lastReadTime = currentTime;
if (readDHT22()) {
float humidity = data[0] + data[1] * 0.1;
float temperature = data[2] + data[3] * 0.1;
Serial.print("Humidity: ");
Serial.print(humidity);
Serial.print(" %\t");
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.println(" °C");
} else {
Serial.println("Failed to read from DHT sensor!");
}
}
}
bool readDHT22() {
byte count = 7;
byte currentBit = 0;
// Initialize data array
for (int i = 0; i < 5; i++) data[i] = 0;
// Send start signal
pinMode(DHTPIN, OUTPUT);
digitalWrite(DHTPIN, LOW);
delay(20);
digitalWrite(DHTPIN, HIGH);
delayMicroseconds(40);
pinMode(DHTPIN, INPUT_PULLUP);
// Wait for response signal
unsigned int loopCount = 10000;
while(digitalRead(DHTPIN) == HIGH) {
if (--loopCount == 0) return false;
}
// Read the response signal
loopCount = 10000;
while(digitalRead(DHTPIN) == LOW) {
if (--loopCount == 0) return false;
}
loopCount = 10000;
while(digitalRead(DHTPIN) == HIGH) {
if (--loopCount == 0) return false;
}
// Read the data
for (int i = 0; i < 40; i++) {
loopCount = 10000;
while(digitalRead(DHTPIN) == LOW) {
if (--loopCount == 0) return false;
}
unsigned long startTime = micros();
loopCount = 10000;
while(digitalRead(DHTPIN) == HIGH) {
if (--loopCount == 0) return false;
}
if (micros() - startTime > 40) {
data[currentBit / 8] |= (1 << (7 - currentBit % 8));
}
currentBit++;
}
// Verify the checksum
if (data[4] == ((data[0] + data[1] + data[2] + data[3]) & 0xFF)) {
return true;
} else {
return false;
}
}