2023-09-19 08:32:49 +03:00
|
|
|
/**
|
|
|
|
* DHT11 Temperature Reader for Arduino
|
|
|
|
* This sketch reads temperature data from the DHT11 sensor and prints the value to the serial port.
|
|
|
|
* It also handles potential error states that might occur during reading.
|
|
|
|
*
|
|
|
|
* Author: Dhruba Saha
|
|
|
|
* Version: 2.0.0
|
|
|
|
* License: MIT
|
|
|
|
*/
|
|
|
|
|
|
|
|
// Include the DHT11 library for interfacing with the sensor.
|
2023-05-30 15:58:45 +03:00
|
|
|
#include <DHT11.h>
|
|
|
|
|
2023-09-20 04:15:14 +03:00
|
|
|
// Create an instance of the DHT11 class.
|
|
|
|
// - For Arduino: Connect the sensor to Digital I/O Pin 2.
|
|
|
|
// - For ESP32: Connect the sensor to pin GPIO2 or P2.
|
|
|
|
// - For ESP8266: Connect the sensor to GPIO2 or D4.
|
2023-05-30 15:58:45 +03:00
|
|
|
DHT11 dht11(2);
|
|
|
|
|
|
|
|
void setup()
|
|
|
|
{
|
2023-09-19 08:32:49 +03:00
|
|
|
// Initialize serial communication to allow debugging and data readout.
|
|
|
|
// Using a baud rate of 9600 bps.
|
|
|
|
Serial.begin(9600);
|
2023-05-30 15:58:45 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
void loop()
|
|
|
|
{
|
2023-09-19 08:32:49 +03:00
|
|
|
// Attempt to read the temperature value from the DHT11 sensor.
|
|
|
|
int temperature = dht11.readTemperature();
|
2023-05-30 15:58:45 +03:00
|
|
|
|
2023-09-19 08:32:49 +03:00
|
|
|
// Check the result of the reading.
|
|
|
|
// If there's no error, print the temperature value.
|
|
|
|
// If there's an error, print the appropriate error message.
|
|
|
|
if (temperature != DHT11::ERROR_CHECKSUM && temperature != DHT11::ERROR_TIMEOUT)
|
2023-05-30 15:58:45 +03:00
|
|
|
{
|
|
|
|
Serial.print("Temperature: ");
|
|
|
|
Serial.print(temperature);
|
2023-09-19 08:32:49 +03:00
|
|
|
Serial.println(" °C");
|
2023-05-30 15:58:45 +03:00
|
|
|
}
|
|
|
|
else
|
|
|
|
{
|
2023-09-19 08:32:49 +03:00
|
|
|
Serial.println(DHT11::getErrorString(temperature));
|
2023-05-30 15:58:45 +03:00
|
|
|
}
|
|
|
|
|
2023-09-19 08:32:49 +03:00
|
|
|
// Wait for 1 seconds before the next reading.
|
|
|
|
delay(1000);
|
2023-05-30 15:58:45 +03:00
|
|
|
}
|