v2.0.0: Enhanced docs, error handling & examples

This commit is contained in:
Dhruba Saha 2023-09-19 11:02:49 +05:30
parent 323e8c192b
commit 542161d1f0
11 changed files with 570 additions and 78 deletions

39
CODE_OF_CONDUCT.md Normal file
View File

@ -0,0 +1,39 @@
# Code of Conduct for DHT11 Arduino Library
## Our Pledge
In the interest of fostering an open and welcoming environment, I, as the author and maintainer of this project, pledge to make participation in this project a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contribute to creating a positive environment include:
- Using welcoming and inclusive language.
- Being respectful of differing viewpoints and experiences.
- Gracefully accepting constructive criticism.
- Focusing on what is best for the community and users.
- Showing empathy towards other community members.
Examples of unacceptable behavior include:
- The use of sexualized language or imagery and unwelcome sexual attention or advances.
- Trolling, insulting/derogatory comments, and personal or political attacks.
- Public or private harassment.
- Publishing others' private information, such as a physical or electronic address, without explicit permission.
- Other conduct which could reasonably be considered inappropriate in a professional setting.
## My Responsibilities
As the sole developer and maintainer, I am responsible for clarifying the standards of acceptable behavior and am expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior can be reported by contacting me directly at dhrubasaha@outlook.com. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. I am obligated to maintain confidentiality with regard to the reporter of an incident.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant](https://www.contributor-covenant.org/), version 1.4, available at [https://www.contributor-covenant.org/version/1/4/code-of-conduct.html](https://www.contributor-covenant.org/version/1/4/code-of-conduct.html)
## Familiarization
All community members, contributors, and participants are encouraged to familiarize themselves with this code of conduct. Adherence to these guidelines helps maintain a positive and respectful environment for everyone involved.

48
CONTRIBUTING.md Normal file
View File

@ -0,0 +1,48 @@
# Contributing to DHT11 Arduino Library
Thank you for considering contributing to the DHT11 Arduino Library. It's community members like you that enhance the usefulness of this library.
## Code of Conduct
I'm committed to fostering a welcoming and open environment. All contributors are expected to adhere to the [DHT11 Arduino Library Code of Conduct](CODE_OF_CONDUCT.md). If you encounter unacceptable behavior, please report it to dhrubasaha@outlook.com.
## How Can I Contribute?
### Reporting Bugs
- **Ensure the bug wasn't previously reported** by searching on GitHub under [Issues](https://github.com/dhrubasaha08/DHT11/issues).
- If you can't find an existing issue addressing the problem, [open a new one](https://github.com/dhrubasaha08/DHT11/issues/new).
### Suggesting Enhancements
Have an idea for an enhancement or a new feature? Please create an issue labeled `enhancement`.
### Pull Requests
1. Fork the repository.
2. Create a new branch (`git checkout -b new-feature`).
3. Commit your changes (`git commit -am 'Add a new feature'`).
4. Push the branch (`git push origin new-feature`).
5. Submit a Pull Request.
## Styleguides
### Git Commit Messages
- Use present tense ("Add feature" not "Added feature").
- Start with a capital letter.
- Limit the first line to 72 characters or fewer.
### Code Styleguide
Stick to the coding conventions evident in the project.
## Additional Notes
### Issue and Pull Request Labels
Possible labels for issues or PRs include:
- `bug` - For bug-related issues.
- `enhancement` - For enhancements or new features.
- `documentation` - For documentation-related issues.

217
README.md
View File

@ -1,35 +1,228 @@
# DHT11
# DHT11 Arduino Library
This is an Arduino library for the DHT11 temperature and humidity sensor. The library provides an easy-to-use interface for reading temperature and humidity data from the DHT11 sensor.
## Table of Contents
- [Introduction](#introduction)
- [Version 2.0.0 Updates](#version-200-updates)
- [How It Works](#how-it-works)
- [Internal Protocol Handling](#internal-protocol-handling)
- [Features](#features)
- [Installation](#installation)
- [Arduino IDE Library Manager](#arduino-ide-library-manager)
- [Installing Manually from GitHub](#installing-manually-from-github)
- [Usage](#usage)
- [Basic Usage](#basic-usage)
- [New Methods in Version 2.0.0](#new-methods-in-version-200)
- [Wiring Details](#wiring-details)
- [Examples](#examples)
- [Error Handling](#error-handling)
- [Troubleshooting](#troubleshooting)
- [FAQ](#faq)
- [Compatibility](#compatibility)
- [Contribute by Testing](#contribute-by-testing)
- [Contributing](#contributing)
- [Code of Conduct](#code-of-conduct)
- [License](#license)
- [External References](#external-references)
## Introduction
This Arduino library is designed for the DHT11 temperature and humidity sensor. It simplifies the process of reading temperature and humidity data, making it easy to integrate the DHT11 sensor into your Arduino projects.
**Author:** [Dhruba Saha](https://github.com/dhrubasaha08)
**Version:** 2.0.0
**License:** [MIT](/LICENSE)
## Version 2.0.0 Updates
- Changed the return type of `readTemperature()` and `readHumidity()` methods from `float` to `int`. This aligns with the DHT11 sensor's 1-degree resolution.
- Enhanced code documentation for easier maintenance and better readability.
- Added the `getErrorString` method to return human-readable error messages based on error codes.
- Major code refactoring for better maintainability and robustness.
- Introduced the [`CONTRIBUTING.md`](CONTRIBUTING.md) file to guide contributors on how to effectively contribute to the library.
- Added a [`CODE_OF_CONDUCT.md`](CODE_OF_CONDUCT.md) to establish community guidelines and expectations for behavior.
- Introduced the [`ReadPlot`](/examples/ReadPlot/ReadPlot.ino) example which uses the Arduino Serial Plotter to display temperature and humidity data. This example provides a visual representation of the sensor's readings, making it easier to monitor environmental conditions in real-time.
## How It Works
The DHT11 sensor provides temperature and humidity data over a single-wire interface. This library handles the low-level communication protocol with the sensor, allowing you to read the temperature and humidity data with simple function calls.
The DHT11 sensor uses a custom single-wire protocol for communication. The basic process for reading data involves:
1. Sending a start signal to the DHT11 sensor.
2. Reading a series of pulses from the sensor representing data bits.
3. Interpreting the received bits to extract temperature and humidity values.
4. Validating the data using a checksum.
The library handles these steps internally, providing the user with a simple interface for reading temperature and humidity.
### Internal Protocol Handling
The library initiates the data request to the DHT11 sensor and then reads a 40-bit data stream in response. The data stream is parsed to obtain accurate temperature and humidity readings. The process of reading data from the DHT11 involves multiple steps:
![](/assets/communication.png)
**Source & Credit :** [Mouser DHT11 Datasheet](https://www.mouser.com/datasheet/2/758/DHT11-Technical-Data-Sheet-Translated-Version-1143054.pdf)
1. **Initialization and Request**:
- The MCU (like an Arduino) sends a start signal by pulling the data line low for at least 18ms.
- The MCU then pulls the line high for 20-40us to indicate that it's ready to receive a response.
2. **DHT11 Response**:
- Upon detecting the start signal from the MCU, the DHT11 sends a response signal.
- This response consists of a 80us low voltage level followed by an 80us high voltage level.
3. **Data Transmission**:
- The DHT11 transmits its data in a series of pulses. Each bit of data is represented by a specific combination of high and low voltage durations.
- A '0' is represented by 50us of low voltage followed by 26-28us of high voltage.
- A '1' is represented by 50us of low voltage followed by 70us of high voltage.
- The DHT11 sends 40 bits of data in total: 16 bits for humidity, 16 bits for temperature, and 8 bits for checksum.
- The checksum is the last 8 bits of the sum of the first 32 bits. It's used to verify data integrity.
4. **Data Interpretation**:
- After reading the 40 bits, the MCU processes the data to extract temperature and humidity values.
- The bits are grouped to form the integral and decimal parts of the temperature and humidity readings, though the DHT11 provides only integer values.
5. **Completion**:
- After data transmission, the DHT11 pulls the data line low for 50us, marking the end of the communication. The MCU then pulls the line high, putting the DHT11 in a low-power standby mode.
This library abstracts these complexities, allowing users to easily read temperature and humidity values with simple function calls. Behind the scenes, it manages the signaling, data reading, and interpretation based on the DHT11's protocol.
When you create an instance of the DHT11 class, you specify the pin that the sensor is connected to. Then, you can call the `readTemperature()` and `readHumidity()` methods to read the temperature and humidity data, respectively. These methods return the temperature in degrees Celsius and the relative humidity in percent, or `-1` if there was an error reading the data.
## Features
- **Easy to use**: Just create an instance of the DHT11 class and call the `readTemperature()` and `readHumidity()` methods.
- **No dependencies**: This library does not depend on any other libraries, so it's easy to install and use.
- **Examples included**: The library comes with example sketches that show you how to use it.
- **Easy to Use**: Easy to use interface for reading temperature and humidity from the DHT11 sensor.
- **No External Dependencies**: The library is standalone and doesn't require any external libraries.
- **Example Sketches**: The library package includes example Arduino sketches to get you started quickly.
- **Error Handling**: The library package includes Error handling mechanisms to ensure robustness.
## Installation
To install the library, download the latest release from this repository and install it using the Arduino IDE's Library Manager.
### Arduino IDE Library Manager
1. Open the Arduino IDE.
2. Go to `Sketch` > `Include Library` > `Manage Libraries...`.
3. In the Library Manager, enter "DHT11" into the search box.
4. Find the DHT11 library in the list and install it.
### Installing Manually from GitHub
1. Download the latest release of the library from this GitHub repository as a ZIP file.
2. Open the Arduino IDE.
3. Go to `Sketch` > `Include Library` > `Add .ZIP Library...`.
4. Navigate to the downloaded ZIP file and select it to install.
## Usage
To use the library, include the `DHT11.h` header file in your sketch, create an instance of the DHT11 class, and call the `readTemperature()` and `readHumidity()` methods. See the example sketches included in the `examples` directory for more details.
### Basic Usage
- Include the `DHT11.h` header file.
- Create an instance of the DHT11 class, specifying the digital pin connected to the sensor's data pin.
- Use `readTemperature()` and `readHumidity()` methods to read the data.
### New Methods in Version 2.0.0
- `getErrorString(int errorCode)`: Returns a human-readable error message based on the provided error code.
### Wiring Details
The DHT11 sensor has three or four pins, depending on the variant:
- **VCC**: Connect to 3.3V or 5V on your MCU (based on your sensor's specification).
- **Data**: Connect to a digital I/O pin on your MCU (not an analog pin). For the provided examples, we use digital pin 2 by default.
- **Ground (GND)**: Connect to the ground of your MCU.
- **NC (No Connect)**: Some variants have this pin. It is not used and can be left unconnected.
Remember to use a pull-up resistor (typically 10kΩ) between the VCC and Data pins for reliable communication.
## Examples
All examples provided use Arduino UNO's digital pin 2 as the default connection to the DHT11 sensor's data pin. Modify this in the code if using a different pin.
- **[Read Humidity](examples/ReadHumidity)**
This example demonstrates how to simply read the humidity value from the DHT11 sensor and display it on the Arduino Serial Monitor. It's a basic introduction to using the library to get humidity data.
- **[Read Temperature and Humidity](examples/ReadTempAndHumidity)**
A more comprehensive example that shows how to read both temperature and humidity values from the DHT11 sensor. Results are displayed on the Arduino Serial Monitor, giving users a complete view of the environment.
- **[Read Temperature](examples/ReadTemperature)**
Similar to the 'Read Humidity' example, but focused solely on reading and displaying the temperature value from the DHT11 sensor. It provides a straightforward way to monitor temperature using the library.
- **[Read Plot](examples/ReadPlot/)**
A visually interactive example that uses the Arduino Serial Plotter to graphically display temperature and humidity data in real-time. This is perfect for those who want a visual representation and trend analysis of the sensor's readings.
## Error Handling
The library provides clear error handling mechanisms. When reading data:
- If there's a timeout while waiting for a response from the sensor, the methods `readTemperature()` and `readHumidity()` return the value `DHT11::ERROR_TIMEOUT`.
- If there's a checksum mismatch indicating data corruption, the methods return the value `DHT11::ERROR_CHECKSUM`.
For translating these error codes to human-readable strings, the library offers the `DHT11::getErrorString(int errorCode)` method.
## Troubleshooting
- **Sensor Not Responding or Constant Timeouts:**
- Ensure the sensor receives the proper voltage (3.3V or 5V).
- Double-check the data pin connection to the Arduino board.
- Restart the Arduino IDE after any changes.
- **Checksum Errors:**
- Ensure minimal distance between the sensor and the Arduino board.
- Check the surrounding environment for electrical noise sources.
- **Inaccurate or Unstable Readings:**
- Give the sensor time to stabilize after powering on.
- Position the sensor away from direct sources of temperature or humidity changes.
- **Library Not Found in Arduino IDE:**
- Confirm the library's correct installation.
- Restart the Arduino IDE.
## FAQ
1. **Is this library designed for the DHT22 sensor as well?**
No. The library caters exclusively to the DHT11 sensor. The DHT22 uses a different data format, necessitating a separate library.
2. **What's the recommended frequency for sensor readings?**
It's best to allow at least 1 second between readings for accurate and stable results.
3. **I'm experiencing persistent timeout errors. What can I do?**
Ensure proper wiring, verify the sensor's power source, and check if the specified data pin in the Arduino code matches your hardware setup.
4. **Has this library been tested on platforms other than the Arduino IDE?**
While it's been primarily tested on the Arduino IDE and Arduino Uno R3 board, it might work on other platforms or boards. However, results may vary.
5. **Is the library compatible with third-party platforms?**
Although tailored for the Arduino IDE, the library might function on other platforms. Still, I don't guarantee compatibility or consistent outcomes on third-party platforms.
## Compatibility
The library has been tested and confirmed to work on the following boards:
- Arduino Uno R3 (ATmega328P - AVR architecture)
I understand that there are many boards and architectures out there, and it's challenging for a single developer to test on all of them.
### Contribute by Testing
If you've successfully used this library on a board not listed above, please consider contributing by letting me know. This will help the community to have a broader understanding of the library's compatibility.
1. Fork the [repository](https://github.com/dhrubasaha08/DHT11).
2. Update the README with the board you've tested.
3. Create a pull request with your changes.
Your contribution will be greatly appreciated, and it will benefit the entire Arduino community.
## Contributing
Contributions to this library are welcome. Please open an issue if you find a bug or have a feature request, and feel free to submit pull requests if you've implemented a new feature or bug fix.
For guidelines on contributing to this project, please see the [`CONTRIBUTING.md`](CONTRIBUTING.md) file.
## Code of Conduct
To understand the community guidelines and expected behavior, please refer to the [`CODE_OF_CONDUCT.md`](CODE_OF_CONDUCT.md) file.
## License
This library is licensed under the MIT License. Please see the `LICENSE` file for more details.
This library is licensed under the `MIT` License. See the [`LICENSE`](LICENSE) file for more details.
## External References
- [DHT11 Datasheet](https://www.mouser.com/datasheet/2/758/DHT11-Technical-Data-Sheet-Translated-Version-1143054.pdf)
- [`DHT11 Datasheet`](https://www.mouser.com/datasheet/2/758/DHT11-Technical-Data-Sheet-Translated-Version-1143054.pdf)

BIN
assets/communication.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 38 KiB

View File

@ -1,21 +1,35 @@
/**
* DHT11 Humidity Reader for Arduino
* This sketch reads humidity 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.
#include <DHT11.h>
// Create an instance of the DHT11 class and set the digital I/O pin.
// Create an instance of the DHT11 class. The sensor is connected to digital I/O pin 2.
DHT11 dht11(2);
void setup()
{
// Initialize serial communication at 115200 baud.
Serial.begin(115200);
// Initialize serial communication to allow debugging and data readout.
// Using a baud rate of 9600 bps.
Serial.begin(9600);
}
void loop()
{
// Read the humidity from the sensor.
float humidity = dht11.readHumidity();
// Attempt to read the humidity value from the DHT11 sensor.
int humidity = dht11.readHumidity();
// If the humidity reading was successful, print it to the serial monitor.
if (humidity != -1)
// Check the result of the reading.
// If there's no error, print the humidity value.
// If there's an error, print the appropriate error message.
if (humidity != DHT11::ERROR_CHECKSUM && humidity != DHT11::ERROR_TIMEOUT)
{
Serial.print("Humidity: ");
Serial.print(humidity);
@ -23,10 +37,9 @@ void loop()
}
else
{
// If the humidity reading failed, print an error message.
Serial.println("Error reading humidity");
Serial.println(DHT11::getErrorString(humidity));
}
// Wait for 2 seconds before the next reading.
delay(2000);
// Wait for 1 seconds before the next reading.
delay(1000);
}

View File

@ -0,0 +1,41 @@
/**
* DHT11 Sensor Reader for Arduino
* This sketch reads temperature and humidity data from the DHT11 sensor and prints the values to the serial plotter.
*
* Author: Dhruba Saha
* Version: 2.0.0
* License: MIT
*/
// Include the DHT11 library for interfacing with the sensor.
#include <DHT11.h>
// Create an instance of the DHT11 class. The sensor is connected to digital I/O pin 2.
DHT11 dht11(2);
void setup()
{
// Initialize serial communication to allow debugging and data readout.
// Using a baud rate of 9600 bps.
Serial.begin(9600);
}
void loop()
{
// Attempt to read the temperature and humidity values from the DHT11 sensor.
int temperature = dht11.readTemperature();
int humidity = dht11.readHumidity();
// Check the results of the readings.
// If there are no errors, print the temperature and humidity values in CSV format.
if (temperature != DHT11::ERROR_CHECKSUM && temperature != DHT11::ERROR_TIMEOUT && humidity != DHT11::ERROR_CHECKSUM && humidity != DHT11::ERROR_TIMEOUT)
{
Serial.print("Temperature:");
Serial.print(temperature);
Serial.print(",Humidity:");
Serial.println(humidity);
}
// Wait for 1 seconds before the next reading.
delay(1000);
}

View File

@ -1,28 +1,41 @@
/**
* DHT11 Sensor Reader for Arduino
* This sketch reads temperature and humidity data from the DHT11 sensor and prints the values 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.
#include <DHT11.h>
// Create an instance of the DHT11 class and set the digital I/O pin.
// Create an instance of the DHT11 class. The sensor is connected to digital I/O pin 2.
DHT11 dht11(2);
void setup()
{
// Initialize serial communication at 115200 baud.
Serial.begin(115200);
// Initialize serial communication to allow debugging and data readout.
// Using a baud rate of 9600 bps.
Serial.begin(9600);
}
void loop()
{
// Read the humidity from the sensor.
float humidity = dht11.readHumidity();
// Attempt to read the temperature and humidity values from the DHT11 sensor.
int temperature = dht11.readTemperature();
int humidity = dht11.readHumidity();
// Read the temperature from the sensor.
float temperature = dht11.readTemperature();
// If the temperature and humidity readings were successful, print them to the serial monitor.
if (temperature != -1 && humidity != -1)
// Check the results of the readings.
// If there are no errors, print the temperature and humidity values.
// If there are errors, print the appropriate error messages.
if (temperature != DHT11::ERROR_CHECKSUM && temperature != DHT11::ERROR_TIMEOUT &&
humidity != DHT11::ERROR_CHECKSUM && humidity != DHT11::ERROR_TIMEOUT)
{
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.println(" C");
Serial.println(" °C");
Serial.print("Humidity: ");
Serial.print(humidity);
@ -30,10 +43,18 @@ void loop()
}
else
{
// If the temperature or humidity reading failed, print an error message.
Serial.println("Error reading data");
if (temperature == DHT11::ERROR_TIMEOUT || temperature == DHT11::ERROR_CHECKSUM)
{
Serial.print("Temperature Reading Error: ");
Serial.println(DHT11::getErrorString(temperature));
}
if (humidity == DHT11::ERROR_TIMEOUT || humidity == DHT11::ERROR_CHECKSUM)
{
Serial.print("Humidity Reading Error: ");
Serial.println(DHT11::getErrorString(humidity));
}
}
// Wait for 2 seconds before the next reading.
delay(2000);
// Wait for 1 seconds before the next reading.
delay(1000);
}

View File

@ -1,32 +1,45 @@
/**
* 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.
#include <DHT11.h>
// Create an instance of the DHT11 class and set the digital I/O pin.
// Create an instance of the DHT11 class. The sensor is connected to digital I/O pin 2.
DHT11 dht11(2);
void setup()
{
// Initialize serial communication at 115200 baud.
Serial.begin(115200);
// Initialize serial communication to allow debugging and data readout.
// Using a baud rate of 9600 bps.
Serial.begin(9600);
}
void loop()
{
// Read the temperature from the sensor.
float temperature = dht11.readTemperature();
// Attempt to read the temperature value from the DHT11 sensor.
int temperature = dht11.readTemperature();
// If the temperature reading was successful, print it to the serial monitor.
if (temperature != -1)
// 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)
{
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.println(" C");
Serial.println(" °C");
}
else
{
// If the temperature reading failed, print an error message.
Serial.println("Error reading temperature");
Serial.println(DHT11::getErrorString(temperature));
}
// Wait for 2 seconds before the next reading.
delay(2000);
// Wait for 1 seconds before the next reading.
delay(1000);
}

View File

@ -1,9 +1,9 @@
name=DHT11
version=1.0.0
author=Dhruba Saha <dhrubasaha@outlook.com>
version=2.0.0
author=Dhruba Saha
maintainer=Dhruba Saha <dhrubasaha@outlook.com>
sentence=A library for the DHT11 temperature and humidity sensor.
paragraph=This library provides an easy-to-use interface for reading temperature and humidity data from a DHT11 sensor. It does not depend on any other libraries.
sentence=An Arduino library for the DHT11 temperature and humidity sensor.
paragraph=This library provides a simple and easy-to-use interface to read temperature and humidity data from a DHT11 sensor.
category=Sensors
url=http://github.com/dhrubasaha08/DHT11
url=https://github.com/dhrubasaha08/DHT11
architectures=*

View File

@ -1,6 +1,20 @@
/**
* DHT11.cpp
* Library for reading temperature and humidity from the DHT11 sensor.
*
* Author: Dhruba Saha
* Version: 2.0.0
* License: MIT
*/
#include "DHT11.h"
// Initializes the pin and sets it to output mode.
/**
* Constructor for the DHT11 class.
* Initializes the pin to be used for communication and sets it to output mode.
*
* @param pin: Digital pin number on the Arduino board to which the DHT11 sensor is connected.
*/
DHT11::DHT11(int pin)
{
_pin = pin;
@ -8,12 +22,26 @@ DHT11::DHT11(int pin)
digitalWrite(_pin, HIGH);
}
// Reads and returns the temperature from the sensor. Returns -1 if the checksum is incorrect.
float DHT11::readTemperature()
/**
* Reads and returns the temperature from the DHT11 sensor.
*
* @return: Temperature value in Celsius. Returns DHT11::ERROR_TIMEOUT if reading times out.
* Returns DHT11::ERROR_CHECKSUM if checksum validation fails.
*/
int DHT11::readTemperature()
{
delay(150);
byte data[5] = {0, 0, 0, 0, 0};
startSignal();
unsigned long timeout_start = millis();
while (digitalRead(_pin) == HIGH)
{
if (millis() - timeout_start > DHT11::TIMEOUT_DURATION)
{
return DHT11::ERROR_TIMEOUT;
}
}
if (digitalRead(_pin) == LOW)
{
@ -21,27 +49,43 @@ float DHT11::readTemperature()
if (digitalRead(_pin) == HIGH)
{
delayMicroseconds(80);
for (int i = 0; i < 5; i++)
{
data[i] = readByte();
if (data[i] == DHT11::ERROR_TIMEOUT)
{
return DHT11::ERROR_TIMEOUT;
}
}
if (data[4] == ((data[0] + data[1] + data[2] + data[3]) & 0xFF))
{
return data[2];
}
}
}
return -1;
return DHT11::ERROR_CHECKSUM;
}
// Reads and returns the humidity from the sensor. Returns -1 if the checksum is incorrect.
float DHT11::readHumidity()
/**
* Reads and returns the humidity from the DHT11 sensor.
*
* @return: Humidity value in percentage. Returns DHT11::ERROR_TIMEOUT if reading times out.
* Returns DHT11::ERROR_CHECKSUM if checksum validation fails.
*/
int DHT11::readHumidity()
{
delay(150);
byte data[5] = {0, 0, 0, 0, 0};
startSignal();
unsigned long timeout_start = millis();
while (digitalRead(_pin) == HIGH)
{
if (millis() - timeout_start > DHT11::TIMEOUT_DURATION)
{
return DHT11::ERROR_TIMEOUT;
}
}
if (digitalRead(_pin) == LOW)
{
@ -49,22 +93,28 @@ float DHT11::readHumidity()
if (digitalRead(_pin) == HIGH)
{
delayMicroseconds(80);
for (int i = 0; i < 5; i++)
{
data[i] = readByte();
if (data[i] == DHT11::ERROR_TIMEOUT)
{
return DHT11::ERROR_TIMEOUT;
}
}
if (data[4] == ((data[0] + data[1] + data[2] + data[3]) & 0xFF))
{
return data[0];
}
}
}
return -1;
return DHT11::ERROR_CHECKSUM;
}
// Reads a byte of data from the sensor.
/**
* Reads a byte of data from the DHT11 sensor during the communication process.
*
* @return: A byte of data read from the sensor.
*/
byte DHT11::readByte()
{
byte value = 0;
@ -84,7 +134,11 @@ byte DHT11::readByte()
return value;
}
// Sends the start signal to the sensor.
/**
* Sends a start signal to the DHT11 sensor to initiate a data read.
* This involves setting the data pin low for a specific duration, then high,
* and finally setting it to input mode to read the data.
*/
void DHT11::startSignal()
{
pinMode(_pin, OUTPUT);
@ -94,3 +148,24 @@ void DHT11::startSignal()
delayMicroseconds(40);
pinMode(_pin, INPUT);
}
/**
* Returns a human-readable error message based on the provided error code.
* This method facilitates easier debugging and user feedback by translating
* numeric error codes into descriptive strings.
*
* @param errorCode The error code for which the description is required.
* @return A descriptive string explaining the error.
*/
String DHT11::getErrorString(int errorCode)
{
switch (errorCode)
{
case DHT11::ERROR_TIMEOUT:
return "Error: Reading from DHT11 timed out.";
case DHT11::ERROR_CHECKSUM:
return "Error: Checksum mismatch while reading from DHT11.";
default:
return "Error: Unknown error code.";
}
}

View File

@ -1,29 +1,78 @@
/**
* DHT11.h
* Header file for the DHT11 library, providing functionalities to interface with
* the DHT11 temperature and humidity sensor.
*
* Author: Dhruba Saha
* Version: 2.0.0
* License: MIT
*/
#ifndef DHT11_h
#define DHT11_h
#include "Arduino.h"
// DHT11 class for reading temperature and humidity data from a DHT11 sensor.
/**
* DHT11 Class
* Provides methods to read temperature and humidity data from the DHT11 sensor.
*/
class DHT11
{
public:
// Takes the pin number as an argument.
/**
* Constructor
* Initializes the data pin to be used for communication with the DHT11 sensor.
*
* @param pin: Digital pin number on the Arduino board to which the DHT11 sensor is connected.
*/
DHT11(int pin);
// Reads and returns the humidity from the sensor. Returns -1 if the checksum is incorrect.
float readHumidity();
/**
* Reads and returns the humidity from the DHT11 sensor.
*
* @return: Humidity value in percentage. Returns DHT11_ERROR_TIMEOUT if reading times out.
* Returns DHT11_ERROR_CHECKSUM if checksum validation fails.
*/
int readHumidity();
// Reads and returns the temperature from the sensor. Returns -1 if the checksum is incorrect.
float readTemperature();
/**
* Reads and returns the temperature from the DHT11 sensor.
*
* @return: Temperature value in Celsius. Returns DHT11_ERROR_TIMEOUT if reading times out.
* Returns DHT11_ERROR_CHECKSUM if checksum validation fails.
*/
int readTemperature();
// Constants to represent error codes.
static const int ERROR_CHECKSUM = 254; // Error code indicating checksum mismatch.
static const int ERROR_TIMEOUT = 253; // Error code indicating a timeout occurred during reading.
static const int TIMEOUT_DURATION = 300; // Duration (in milliseconds) to wait before timing out.
/**
* Returns a human-readable error message based on the provided error code.
*
* @param errorCode: The error code for which the message is required.
* @return: A string describing the error.
*/
static String getErrorString(int errorCode);
private:
int _pin;
int _pin; // Pin number used for communication with the DHT11 sensor.
// Reads a byte of data from the sensor.
/**
* Reads a byte of data from the DHT11 sensor.
*
* @return: A byte of data read from the sensor.
*/
byte readByte();
// Sends the start signal to the sensor.
/**
* Sends a start signal to the DHT11 sensor to initiate a data read.
* This involves setting the data pin low for a specific duration, then high,
* and finally setting it to input mode to read the data.
*/
void startSignal();
};
#endif
#endif