#include <DHT.h> // include the library for our sensor
#define DHTPIN 2 // define the pin where the sensor is connected
#define DHTTYPE DHT22 // define the type of the sensor
DHT dht(DHTPIN, DHTTYPE); // class of the library to create an object
void setup() { // function to start when we power the board or reseting
Serial.begin(115200); // initialization
pinMode(13, OUTPUT); // for the alarm led
dht.begin(); // initialization of the sensor
delay(1000); // delay 1 second to skip the unstable phase
Serial.println("AM2302 Is Ready!"); // to see that the sensor connected successfully
// print the headers
Serial.print("Time (ms), Humidity (%), Temperature (C), Sense Temperature (C)");
// check the led
digitalWrite(13, HIGH); // light led
delay(500);
digitalWrite(13, LOW); // close led
}
void loop() { // function that runs again and again for ever after the setup until we reset or cut off the power
float humidity=dht.readHumidity(); // read the humidity measumerement
float temperature=dht.readTemperature(); // read the temperature measurement
float sense=dht.computeHeatIndex(temperature, humidity, false); // calculate the sense temperature due to humidity
// print time humidity, temperature and sense of temperature values
Serial.print(millis());
Serial.print(", ");
Serial.print(humidity);
Serial.print(", ");
Serial.print(temperature);
Serial.print(", ");
Serial.println(sense); // print with new line at the end
// for extreme temperatures give an alarm
if (temperature>=40 || temperature<=0)
{
alert_blink();
}
else
{
digitalWrite(13, LOW); // to be sure the led if off
delay(2000); // take a measure every 2 seconds
}
}
void alert_blink() // alarm function for the led blink
{ // total delay same as if we don't have an alarm (can be different)
digitalWrite(13, HIGH);
delay(400);
digitalWrite(13, LOW);
delay(400);
digitalWrite(13, HIGH);
delay(400);
digitalWrite(13, LOW);
delay(400);
digitalWrite(13, HIGH);
delay(400);
digitalWrite(13, LOW);
}