libraries: switch to dht11.h from keyestudio

a93d1575a96c77b5cc9184bf3ceca3ecf9d61779  /home/vbatts/KS0530 Keyestudio Solar Tracking Kit.zip
fea14b18807e3dac4b112354eefb76a5e0f76c4b  /home/vbatts/KS0530 Keyestudio Solar Tracking Kit/Libraries/Dht11.zip
This commit is contained in:
Vincent Batts 2024-07-29 16:47:45 -04:00
parent a334d75815
commit 636263d2d3
50 changed files with 256 additions and 2393 deletions

View file

@ -1,13 +0,0 @@
# Contribution Guidlines
This library is the culmination of the expertise of many members of the open source community who have dedicated their time and hard work. The best way to ask for help or propose a new idea is to [create a new issue](https://github.com/adafruit/DHT-sensor-library/issues/new) while creating a Pull Request with your code changes allows you to share your own innovations with the rest of the community.
The following are some guidelines to observe when creating issues or PRs:
- Be friendly; it is important that we can all enjoy a safe space as we are all working on the same project and it is okay for people to have different ideas
- [Use code blocks](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet#code); it helps us help you when we can read your code! On that note also refrain from pasting more than 30 lines of code in a post, instead [create a gist](https://gist.github.com/) if you need to share large snippets
- Use reasonable titles; refrain from using overly long or capitalized titles as they are usually annoying and do little to encourage others to help :smile:
- Be detailed; refrain from mentioning code problems without sharing your source code and always give information regarding your board and version of the library

View file

@ -1,390 +0,0 @@
/*!
* @file DHT.cpp
*
* @mainpage DHT series of low cost temperature/humidity sensors.
*
* @section intro_sec Introduction
*
* This is a library for DHT series of low cost temperature/humidity sensors.
*
* You must have Adafruit Unified Sensor Library library installed to use this
* class.
*
* Adafruit invests time and resources providing this open source code,
* please support Adafruit andopen-source hardware by purchasing products
* from Adafruit!
*
* @section author Author
*
* Written by Adafruit Industries.
*
* @section license License
*
* MIT license, all text above must be included in any redistribution
*/
#include "DHT.h"
#define MIN_INTERVAL 2000 /**< min interval value */
#define TIMEOUT \
UINT32_MAX /**< Used programmatically for timeout. \
Not a timeout duration. Type: uint32_t. */
/*!
* @brief Instantiates a new DHT class
* @param pin
* pin number that sensor is connected
* @param type
* type of sensor
* @param count
* number of sensors
*/
DHT::DHT(uint8_t pin, uint8_t type, uint8_t count) {
(void)count; // Workaround to avoid compiler warning.
_pin = pin;
_type = type;
#ifdef __AVR
_bit = digitalPinToBitMask(pin);
_port = digitalPinToPort(pin);
#endif
_maxcycles =
microsecondsToClockCycles(1000); // 1 millisecond timeout for
// reading pulses from DHT sensor.
// Note that count is now ignored as the DHT reading algorithm adjusts itself
// based on the speed of the processor.
}
/*!
* @brief Setup sensor pins and set pull timings
* @param usec
* Optionally pass pull-up time (in microseconds) before DHT reading
*starts. Default is 55 (see function declaration in DHT.h).
*/
void DHT::begin(uint8_t usec) {
// set up the pins!
pinMode(_pin, INPUT_PULLUP);
// Using this value makes sure that millis() - lastreadtime will be
// >= MIN_INTERVAL right away. Note that this assignment wraps around,
// but so will the subtraction.
_lastreadtime = millis() - MIN_INTERVAL;
DEBUG_PRINT("DHT max clock cycles: ");
DEBUG_PRINTLN(_maxcycles, DEC);
pullTime = usec;
}
/*!
* @brief Read temperature
* @param S
* Scale. Boolean value:
* - true = Fahrenheit
* - false = Celcius
* @param force
* true if in force mode
* @return Temperature value in selected scale
*/
float DHT::readTemperature(bool S, bool force) {
float f = NAN;
if (read(force)) {
switch (_type) {
case DHT11:
f = data[2];
if (data[3] & 0x80) {
f = -1 - f;
}
f += (data[3] & 0x0f) * 0.1;
if (S) {
f = convertCtoF(f);
}
break;
case DHT12:
f = data[2];
f += (data[3] & 0x0f) * 0.1;
if (data[2] & 0x80) {
f *= -1;
}
if (S) {
f = convertCtoF(f);
}
break;
case DHT22:
case DHT21:
f = ((word)(data[2] & 0x7F)) << 8 | data[3];
f *= 0.1;
if (data[2] & 0x80) {
f *= -1;
}
if (S) {
f = convertCtoF(f);
}
break;
}
}
return f;
}
/*!
* @brief Converts Celcius to Fahrenheit
* @param c
* value in Celcius
* @return float value in Fahrenheit
*/
float DHT::convertCtoF(float c) { return c * 1.8 + 32; }
/*!
* @brief Converts Fahrenheit to Celcius
* @param f
* value in Fahrenheit
* @return float value in Celcius
*/
float DHT::convertFtoC(float f) { return (f - 32) * 0.55555; }
/*!
* @brief Read Humidity
* @param force
* force read mode
* @return float value - humidity in percent
*/
float DHT::readHumidity(bool force) {
float f = NAN;
if (read(force)) {
switch (_type) {
case DHT11:
case DHT12:
f = data[0] + data[1] * 0.1;
break;
case DHT22:
case DHT21:
f = ((word)data[0]) << 8 | data[1];
f *= 0.1;
break;
}
}
return f;
}
/*!
* @brief Compute Heat Index
* Simplified version that reads temp and humidity from sensor
* @param isFahrenheit
* true if fahrenheit, false if celcius
*(default true)
* @return float heat index
*/
float DHT::computeHeatIndex(bool isFahrenheit) {
float hi = computeHeatIndex(readTemperature(isFahrenheit), readHumidity(),
isFahrenheit);
return hi;
}
/*!
* @brief Compute Heat Index
* Using both Rothfusz and Steadman's equations
* (http://www.wpc.ncep.noaa.gov/html/heatindex_equation.shtml)
* @param temperature
* temperature in selected scale
* @param percentHumidity
* humidity in percent
* @param isFahrenheit
* true if fahrenheit, false if celcius
* @return float heat index
*/
float DHT::computeHeatIndex(float temperature, float percentHumidity,
bool isFahrenheit) {
float hi;
if (!isFahrenheit)
temperature = convertCtoF(temperature);
hi = 0.5 * (temperature + 61.0 + ((temperature - 68.0) * 1.2) +
(percentHumidity * 0.094));
if (hi > 79) {
hi = -42.379 + 2.04901523 * temperature + 10.14333127 * percentHumidity +
-0.22475541 * temperature * percentHumidity +
-0.00683783 * pow(temperature, 2) +
-0.05481717 * pow(percentHumidity, 2) +
0.00122874 * pow(temperature, 2) * percentHumidity +
0.00085282 * temperature * pow(percentHumidity, 2) +
-0.00000199 * pow(temperature, 2) * pow(percentHumidity, 2);
if ((percentHumidity < 13) && (temperature >= 80.0) &&
(temperature <= 112.0))
hi -= ((13.0 - percentHumidity) * 0.25) *
sqrt((17.0 - abs(temperature - 95.0)) * 0.05882);
else if ((percentHumidity > 85.0) && (temperature >= 80.0) &&
(temperature <= 87.0))
hi += ((percentHumidity - 85.0) * 0.1) * ((87.0 - temperature) * 0.2);
}
return isFahrenheit ? hi : convertFtoC(hi);
}
/*!
* @brief Read value from sensor or return last one from less than two
*seconds.
* @param force
* true if using force mode
* @return float value
*/
bool DHT::read(bool force) {
// Check if sensor was read less than two seconds ago and return early
// to use last reading.
uint32_t currenttime = millis();
if (!force && ((currenttime - _lastreadtime) < MIN_INTERVAL)) {
return _lastresult; // return last correct measurement
}
_lastreadtime = currenttime;
// Reset 40 bits of received data to zero.
data[0] = data[1] = data[2] = data[3] = data[4] = 0;
#if defined(ESP8266)
yield(); // Handle WiFi / reset software watchdog
#endif
// Send start signal. See DHT datasheet for full signal diagram:
// http://www.adafruit.com/datasheets/Digital%20humidity%20and%20temperature%20sensor%20AM2302.pdf
// Go into high impedence state to let pull-up raise data line level and
// start the reading process.
pinMode(_pin, INPUT_PULLUP);
delay(1);
// First set data line low for a period according to sensor type
pinMode(_pin, OUTPUT);
digitalWrite(_pin, LOW);
switch (_type) {
case DHT22:
case DHT21:
delayMicroseconds(1100); // data sheet says "at least 1ms"
break;
case DHT11:
default:
delay(20); // data sheet says at least 18ms, 20ms just to be safe
break;
}
uint32_t cycles[80];
{
// End the start signal by setting data line high for 40 microseconds.
pinMode(_pin, INPUT_PULLUP);
// Delay a moment to let sensor pull data line low.
delayMicroseconds(pullTime);
// Now start reading the data line to get the value from the DHT sensor.
// Turn off interrupts temporarily because the next sections
// are timing critical and we don't want any interruptions.
InterruptLock lock;
// First expect a low signal for ~80 microseconds followed by a high signal
// for ~80 microseconds again.
if (expectPulse(LOW) == TIMEOUT) {
DEBUG_PRINTLN(F("DHT timeout waiting for start signal low pulse."));
_lastresult = false;
return _lastresult;
}
if (expectPulse(HIGH) == TIMEOUT) {
DEBUG_PRINTLN(F("DHT timeout waiting for start signal high pulse."));
_lastresult = false;
return _lastresult;
}
// Now read the 40 bits sent by the sensor. Each bit is sent as a 50
// microsecond low pulse followed by a variable length high pulse. If the
// high pulse is ~28 microseconds then it's a 0 and if it's ~70 microseconds
// then it's a 1. We measure the cycle count of the initial 50us low pulse
// and use that to compare to the cycle count of the high pulse to determine
// if the bit is a 0 (high state cycle count < low state cycle count), or a
// 1 (high state cycle count > low state cycle count). Note that for speed
// all the pulses are read into a array and then examined in a later step.
for (int i = 0; i < 80; i += 2) {
cycles[i] = expectPulse(LOW);
cycles[i + 1] = expectPulse(HIGH);
}
} // Timing critical code is now complete.
// Inspect pulses and determine which ones are 0 (high state cycle count < low
// state cycle count), or 1 (high state cycle count > low state cycle count).
for (int i = 0; i < 40; ++i) {
uint32_t lowCycles = cycles[2 * i];
uint32_t highCycles = cycles[2 * i + 1];
if ((lowCycles == TIMEOUT) || (highCycles == TIMEOUT)) {
DEBUG_PRINTLN(F("DHT timeout waiting for pulse."));
_lastresult = false;
return _lastresult;
}
data[i / 8] <<= 1;
// Now compare the low and high cycle times to see if the bit is a 0 or 1.
if (highCycles > lowCycles) {
// High cycles are greater than 50us low cycle count, must be a 1.
data[i / 8] |= 1;
}
// Else high cycles are less than (or equal to, a weird case) the 50us low
// cycle count so this must be a zero. Nothing needs to be changed in the
// stored data.
}
DEBUG_PRINTLN(F("Received from DHT:"));
DEBUG_PRINT(data[0], HEX);
DEBUG_PRINT(F(", "));
DEBUG_PRINT(data[1], HEX);
DEBUG_PRINT(F(", "));
DEBUG_PRINT(data[2], HEX);
DEBUG_PRINT(F(", "));
DEBUG_PRINT(data[3], HEX);
DEBUG_PRINT(F(", "));
DEBUG_PRINT(data[4], HEX);
DEBUG_PRINT(F(" =? "));
DEBUG_PRINTLN((data[0] + data[1] + data[2] + data[3]) & 0xFF, HEX);
// Check we read 40 bits and that the checksum matches.
if (data[4] == ((data[0] + data[1] + data[2] + data[3]) & 0xFF)) {
_lastresult = true;
return _lastresult;
} else {
DEBUG_PRINTLN(F("DHT checksum failure!"));
_lastresult = false;
return _lastresult;
}
}
// Expect the signal line to be at the specified level for a period of time and
// return a count of loop cycles spent at that level (this cycle count can be
// used to compare the relative time of two pulses). If more than a millisecond
// ellapses without the level changing then the call fails with a 0 response.
// This is adapted from Arduino's pulseInLong function (which is only available
// in the very latest IDE versions):
// https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/wiring_pulse.c
uint32_t DHT::expectPulse(bool level) {
// F_CPU is not be known at compile time on platforms such as STM32F103.
// The preprocessor seems to evaluate it to zero in that case.
#if (F_CPU > 16000000L) || (F_CPU == 0L)
uint32_t count = 0;
#else
uint16_t count = 0; // To work fast enough on slower AVR boards
#endif
// On AVR platforms use direct GPIO port access as it's much faster and better
// for catching pulses that are 10's of microseconds in length:
#ifdef __AVR
uint8_t portState = level ? _bit : 0;
while ((*portInputRegister(_port) & _bit) == portState) {
if (count++ >= _maxcycles) {
return TIMEOUT; // Exceeded timeout, fail.
}
}
// Otherwise fall back to using digitalRead (this seems to be necessary on
// ESP8266 right now, perhaps bugs in direct port access functions?).
#else
while (digitalRead(_pin) == level) {
if (count++ >= _maxcycles) {
return TIMEOUT; // Exceeded timeout, fail.
}
}
#endif
return count;
}

View file

@ -1,109 +0,0 @@
/*!
* @file DHT.h
*
* This is a library for DHT series of low cost temperature/humidity sensors.
*
* You must have Adafruit Unified Sensor Library library installed to use this
* class.
*
* Adafruit invests time and resources providing this open source code,
* please support Adafruit andopen-source hardware by purchasing products
* from Adafruit!
*
* Written by Adafruit Industries.
*
* MIT license, all text above must be included in any redistribution
*/
#ifndef DHT_H
#define DHT_H
#include "Arduino.h"
/* Uncomment to enable printing out nice debug messages. */
//#define DHT_DEBUG
#define DEBUG_PRINTER \
Serial /**< Define where debug output will be printed. \
*/
/* Setup debug printing macros. */
#ifdef DHT_DEBUG
#define DEBUG_PRINT(...) \
{ DEBUG_PRINTER.print(__VA_ARGS__); }
#define DEBUG_PRINTLN(...) \
{ DEBUG_PRINTER.println(__VA_ARGS__); }
#else
#define DEBUG_PRINT(...) \
{} /**< Debug Print Placeholder if Debug is disabled */
#define DEBUG_PRINTLN(...) \
{} /**< Debug Print Line Placeholder if Debug is disabled */
#endif
/* Define types of sensors. */
static const uint8_t DHT11{11}; /**< DHT TYPE 11 */
static const uint8_t DHT12{12}; /**< DHY TYPE 12 */
static const uint8_t DHT21{21}; /**< DHT TYPE 21 */
static const uint8_t DHT22{22}; /**< DHT TYPE 22 */
static const uint8_t AM2301{21}; /**< AM2301 */
#if defined(TARGET_NAME) && (TARGET_NAME == ARDUINO_NANO33BLE)
#ifndef microsecondsToClockCycles
/*!
* As of 7 Sep 2020 the Arduino Nano 33 BLE boards do not have
* microsecondsToClockCycles defined.
*/
#define microsecondsToClockCycles(a) ((a) * (SystemCoreClock / 1000000L))
#endif
#endif
/*!
* @brief Class that stores state and functions for DHT
*/
class DHT {
public:
DHT(uint8_t pin, uint8_t type, uint8_t count = 6);
void begin(uint8_t usec = 55);
float readTemperature(bool S = false, bool force = false);
float convertCtoF(float);
float convertFtoC(float);
float computeHeatIndex(bool isFahrenheit = true);
float computeHeatIndex(float temperature, float percentHumidity,
bool isFahrenheit = true);
float readHumidity(bool force = false);
bool read(bool force = false);
private:
uint8_t data[5];
uint8_t _pin, _type;
#ifdef __AVR
// Use direct GPIO access on an 8-bit AVR so keep track of the port and
// bitmask for the digital pin connected to the DHT. Other platforms will use
// digitalRead.
uint8_t _bit, _port;
#endif
uint32_t _lastreadtime, _maxcycles;
bool _lastresult;
uint8_t pullTime; // Time (in usec) to pull up data line before reading
uint32_t expectPulse(bool level);
};
/*!
* @brief Class that defines Interrupt Lock Avaiability
*/
class InterruptLock {
public:
InterruptLock() {
#if !defined(ARDUINO_ARCH_NRF52)
noInterrupts();
#endif
}
~InterruptLock() {
#if !defined(ARDUINO_ARCH_NRF52)
interrupts();
#endif
}
};
#endif

View file

@ -1,239 +0,0 @@
/*!
* @file DHT_U.cpp
*
* Temperature & Humidity Unified Sensor Library
*
* This is a library for DHT series of low cost temperature/humidity sensors.
*
* You must have Adafruit Unified Sensor Library library installed to use this
* class.
*
* Adafruit invests time and resources providing this open source code,
* please support Adafruit andopen-source hardware by purchasing products
* from Adafruit!
*/
#include "DHT_U.h"
/*!
* @brief Instantiates a new DHT_Unified class
* @param pin
* pin number that sensor is connected
* @param type
* type of sensor
* @param count
* number of sensors
* @param tempSensorId
* temperature sensor id
* @param humiditySensorId
* humidity sensor id
*/
DHT_Unified::DHT_Unified(uint8_t pin, uint8_t type, uint8_t count,
int32_t tempSensorId, int32_t humiditySensorId)
: _dht(pin, type, count), _type(type), _temp(this, tempSensorId),
_humidity(this, humiditySensorId) {}
/*!
* @brief Setup sensor (calls begin on It)
*/
void DHT_Unified::begin() { _dht.begin(); }
/*!
* @brief Sets sensor name
* @param sensor
* Sensor that will be set
*/
void DHT_Unified::setName(sensor_t *sensor) {
switch (_type) {
case DHT11:
strncpy(sensor->name, "DHT11", sizeof(sensor->name) - 1);
break;
case DHT12:
strncpy(sensor->name, "DHT12", sizeof(sensor->name) - 1);
break;
case DHT21:
strncpy(sensor->name, "DHT21", sizeof(sensor->name) - 1);
break;
case DHT22:
strncpy(sensor->name, "DHT22", sizeof(sensor->name) - 1);
break;
default:
// TODO: Perhaps this should be an error? However main DHT library doesn't
// enforce restrictions on the sensor type value. Pick a generic name for
// now.
strncpy(sensor->name, "DHT?", sizeof(sensor->name) - 1);
break;
}
sensor->name[sizeof(sensor->name) - 1] = 0;
}
/*!
* @brief Sets Minimum Delay Value
* @param sensor
* Sensor that will be set
*/
void DHT_Unified::setMinDelay(sensor_t *sensor) {
switch (_type) {
case DHT11:
sensor->min_delay = 1000000L; // 1 second (in microseconds)
break;
case DHT12:
sensor->min_delay = 2000000L; // 2 second (in microseconds)
break;
case DHT21:
sensor->min_delay = 2000000L; // 2 seconds (in microseconds)
break;
case DHT22:
sensor->min_delay = 2000000L; // 2 seconds (in microseconds)
break;
default:
// Default to slowest sample rate in case of unknown type.
sensor->min_delay = 2000000L; // 2 seconds (in microseconds)
break;
}
}
/*!
* @brief Instantiates a new DHT_Unified Temperature Class
* @param parent
* Parent Sensor
* @param id
* Sensor id
*/
DHT_Unified::Temperature::Temperature(DHT_Unified *parent, int32_t id)
: _parent(parent), _id(id) {}
/*!
* @brief Reads the sensor and returns the data as a sensors_event_t
* @param event
* @return always returns true
*/
bool DHT_Unified::Temperature::getEvent(sensors_event_t *event) {
// Clear event definition.
memset(event, 0, sizeof(sensors_event_t));
// Populate sensor reading values.
event->version = sizeof(sensors_event_t);
event->sensor_id = _id;
event->type = SENSOR_TYPE_AMBIENT_TEMPERATURE;
event->timestamp = millis();
event->temperature = _parent->_dht.readTemperature();
return true;
}
/*!
* @brief Provides the sensor_t data for this sensor
* @param sensor
*/
void DHT_Unified::Temperature::getSensor(sensor_t *sensor) {
// Clear sensor definition.
memset(sensor, 0, sizeof(sensor_t));
// Set sensor name.
_parent->setName(sensor);
// Set version and ID
sensor->version = DHT_SENSOR_VERSION;
sensor->sensor_id = _id;
// Set type and characteristics.
sensor->type = SENSOR_TYPE_AMBIENT_TEMPERATURE;
_parent->setMinDelay(sensor);
switch (_parent->_type) {
case DHT11:
sensor->max_value = 50.0F;
sensor->min_value = 0.0F;
sensor->resolution = 2.0F;
break;
case DHT12:
sensor->max_value = 60.0F;
sensor->min_value = -20.0F;
sensor->resolution = 0.5F;
break;
case DHT21:
sensor->max_value = 80.0F;
sensor->min_value = -40.0F;
sensor->resolution = 0.1F;
break;
case DHT22:
sensor->max_value = 125.0F;
sensor->min_value = -40.0F;
sensor->resolution = 0.1F;
break;
default:
// Unknown type, default to 0.
sensor->max_value = 0.0F;
sensor->min_value = 0.0F;
sensor->resolution = 0.0F;
break;
}
}
/*!
* @brief Instantiates a new DHT_Unified Humidity Class
* @param parent
* Parent Sensor
* @param id
* Sensor id
*/
DHT_Unified::Humidity::Humidity(DHT_Unified *parent, int32_t id)
: _parent(parent), _id(id) {}
/*!
* @brief Reads the sensor and returns the data as a sensors_event_t
* @param event
* @return always returns true
*/
bool DHT_Unified::Humidity::getEvent(sensors_event_t *event) {
// Clear event definition.
memset(event, 0, sizeof(sensors_event_t));
// Populate sensor reading values.
event->version = sizeof(sensors_event_t);
event->sensor_id = _id;
event->type = SENSOR_TYPE_RELATIVE_HUMIDITY;
event->timestamp = millis();
event->relative_humidity = _parent->_dht.readHumidity();
return true;
}
/*!
* @brief Provides the sensor_t data for this sensor
* @param sensor
*/
void DHT_Unified::Humidity::getSensor(sensor_t *sensor) {
// Clear sensor definition.
memset(sensor, 0, sizeof(sensor_t));
// Set sensor name.
_parent->setName(sensor);
// Set version and ID
sensor->version = DHT_SENSOR_VERSION;
sensor->sensor_id = _id;
// Set type and characteristics.
sensor->type = SENSOR_TYPE_RELATIVE_HUMIDITY;
_parent->setMinDelay(sensor);
switch (_parent->_type) {
case DHT11:
sensor->max_value = 80.0F;
sensor->min_value = 20.0F;
sensor->resolution = 5.0F;
break;
case DHT12:
sensor->max_value = 95.0F;
sensor->min_value = 20.0F;
sensor->resolution = 5.0F;
break;
case DHT21:
sensor->max_value = 100.0F;
sensor->min_value = 0.0F;
sensor->resolution = 0.1F;
break;
case DHT22:
sensor->max_value = 100.0F;
sensor->min_value = 0.0F;
sensor->resolution = 0.1F;
break;
default:
// Unknown type, default to 0.
sensor->max_value = 0.0F;
sensor->min_value = 0.0F;
sensor->resolution = 0.0F;
break;
}
}

View file

@ -1,101 +0,0 @@
/*!
* @file DHT_U.h
*
* DHT Temperature & Humidity Unified Sensor Library<Paste>
*
* Adafruit invests time and resources providing this open source code,
* please support Adafruit andopen-source hardware by purchasing products
* from Adafruit!
*
* Written by Tony DiCola (Adafruit Industries) 2014.
*
* MIT license, all text above must be included in any redistribution
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#ifndef DHT_U_H
#define DHT_U_H
#include <Adafruit_Sensor.h>
#include <DHT.h>
#define DHT_SENSOR_VERSION 1 /**< Sensor Version */
/*!
* @brief Class that stores state and functions for interacting with
* DHT_Unified.
*/
class DHT_Unified {
public:
DHT_Unified(uint8_t pin, uint8_t type, uint8_t count = 6,
int32_t tempSensorId = -1, int32_t humiditySensorId = -1);
void begin();
/*!
* @brief Class that stores state and functions about Temperature
*/
class Temperature : public Adafruit_Sensor {
public:
Temperature(DHT_Unified *parent, int32_t id);
bool getEvent(sensors_event_t *event);
void getSensor(sensor_t *sensor);
private:
DHT_Unified *_parent;
int32_t _id;
};
/*!
* @brief Class that stores state and functions about Humidity
*/
class Humidity : public Adafruit_Sensor {
public:
Humidity(DHT_Unified *parent, int32_t id);
bool getEvent(sensors_event_t *event);
void getSensor(sensor_t *sensor);
private:
DHT_Unified *_parent;
int32_t _id;
};
/*!
* @brief Returns temperature stored in _temp
* @return Temperature value
*/
Temperature temperature() { return _temp; }
/*!
* @brief Returns humidity stored in _humidity
* @return Humidity value
*/
Humidity humidity() { return _humidity; }
private:
DHT _dht;
uint8_t _type;
Temperature _temp;
Humidity _humidity;
void setName(sensor_t *sensor);
void setMinDelay(sensor_t *sensor);
};
#endif

View file

@ -1,58 +0,0 @@
# DHT sensor library [![Build Status](https://github.com/adafruit/DHT-sensor-library/workflows/Arduino%20Library%20CI/badge.svg)](https://github.com/adafruit/DHT-sensor-library/actions)
## Description
An Arduino library for the DHT series of low-cost temperature/humidity sensors.
You can find DHT tutorials [here](https://learn.adafruit.com/dht).
# Dependencies
* [Adafruit Unified Sensor Driver](https://github.com/adafruit/Adafruit_Sensor)
# Contributing
Contributions are welcome! Not only youll encourage the development of the library, but youll also learn how to best use the library and probably some C++ too
Please read our [Code of Conduct](https://github.com/adafruit/DHT-sensor-library/blob/master/CODE_OF_CONDUCT.md>)
before contributing to help this project stay welcoming.
## Documentation and doxygen
Documentation is produced by doxygen. Contributions should include documentation for any new code added.
Some examples of how to use doxygen can be found in these guide pages:
https://learn.adafruit.com/the-well-automated-arduino-library/doxygen
https://learn.adafruit.com/the-well-automated-arduino-library/doxygen-tips
Written by Adafruit Industries based on work by:
* T. DiCola
* P. Y. Dragon
* L. Fried
* J. Hoffmann
* M. Kooijman
* J. M. Dana
* S. Conaway
* S. IJskes
* T. Forbes
* B. C
* T. J Myers
* L. Sørup
* per1234
* O. Duffy
* matthiasdanner
* J. Lim
* G. Ambrozio
* chelmi
* adams13x13
* Spacefish
* I. Scheller
* C. Miller
* 7eggert
MIT license, check license.txt for more information
All text above must be included in any redistribution
To install, use the Arduino Library Manager and search for "DHT sensor library" and install the library.

View file

@ -1,127 +0,0 @@
# Adafruit Community Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as
contributors and leaders pledge to making participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, gender identity and expression, level or type of
experience, education, socio-economic status, nationality, personal appearance,
race, religion, or sexual identity and orientation.
## Our Standards
We are committed to providing a friendly, safe and welcoming environment for
all.
Examples of behavior that contributes to creating a positive environment
include:
* Be kind and courteous to others
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Collaborating with other community members
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and sexual attention or advances
* The use of inappropriate images, including in a community member's avatar
* The use of inappropriate language, including in a community member's nickname
* Any spamming, flaming, baiting or other attention-stealing behavior
* Excessive or unwelcome helping; answering outside the scope of the question
asked
* 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
The goal of the standards and moderation guidelines outlined here is to build
and maintain a respectful community. We ask that you dont just aim to be
"technically unimpeachable", but rather try to be your best self.
We value many things beyond technical expertise, including collaboration and
supporting others within our community. Providing a positive experience for
other community members can have a much more significant impact than simply
providing the correct answer.
## Our Responsibilities
Project leaders are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.
Project leaders have the right and responsibility to remove, edit, or
reject messages, comments, commits, code, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any community member for other behaviors that they deem
inappropriate, threatening, offensive, or harmful.
## Moderation
Instances of behaviors that violate the Adafruit Community Code of Conduct
may be reported by any member of the community. Community members are
encouraged to report these situations, including situations they witness
involving other community members.
You may report in the following ways:
In any situation, you may send an email to <support@adafruit.com>.
On the Adafruit Discord, you may send an open message from any channel
to all Community Helpers by tagging @community helpers. You may also send an
open message from any channel, or a direct message to @kattni#1507,
@tannewt#4653, @Dan Halbert#1614, @cater#2442, @sommersoft#0222, or
@Andon#8175.
Email and direct message reports will be kept confidential.
In situations on Discord where the issue is particularly egregious, possibly
illegal, requires immediate action, or violates the Discord terms of service,
you should also report the message directly to Discord.
These are the steps for upholding our communitys standards of conduct.
1. Any member of the community may report any situation that violates the
Adafruit Community Code of Conduct. All reports will be reviewed and
investigated.
2. If the behavior is an egregious violation, the community member who
committed the violation may be banned immediately, without warning.
3. Otherwise, moderators will first respond to such behavior with a warning.
4. Moderators follow a soft "three strikes" policy - the community member may
be given another chance, if they are receptive to the warning and change their
behavior.
5. If the community member is unreceptive or unreasonable when warned by a
moderator, or the warning goes unheeded, they may be banned for a first or
second offense. Repeated offenses will result in the community member being
banned.
## Scope
This Code of Conduct and the enforcement policies listed above apply to all
Adafruit Community venues. This includes but is not limited to any community
spaces (both public and private), the entire Adafruit Discord server, and
Adafruit GitHub repositories. Examples of Adafruit Community spaces include
but are not limited to meet-ups, audio chats on the Adafruit Discord, or
interaction at a conference.
This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community. As a community
member, you are representing our community, and are expected to behave
accordingly.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
version 1.4, available at
<https://www.contributor-covenant.org/version/1/4/code-of-conduct.html>,
and the [Rust Code of Conduct](https://www.rust-lang.org/en-US/conduct.html).
For other projects adopting the Adafruit Community Code of
Conduct, please contact the maintainers of those projects for enforcement.
If you wish to use this code of conduct for your own project, consider
explicitly mentioning your moderation policy or making a copy with your
own moderation policy so as to avoid confusion.

View file

@ -1,85 +0,0 @@
// DHT Temperature & Humidity Sensor
// Unified Sensor Library Example
// Written by Tony DiCola for Adafruit Industries
// Released under an MIT license.
// REQUIRES the following Arduino libraries:
// - DHT Sensor Library: https://github.com/adafruit/DHT-sensor-library
// - Adafruit Unified Sensor Lib: https://github.com/adafruit/Adafruit_Sensor
#include <Adafruit_Sensor.h>
#include <DHT.h>
#include <DHT_U.h>
#define DHTPIN 2 // Digital pin connected to the DHT sensor
// Feather HUZZAH ESP8266 note: use pins 3, 4, 5, 12, 13 or 14 --
// Pin 15 can work but DHT must be disconnected during program upload.
// Uncomment the type of sensor in use:
//#define DHTTYPE DHT11 // DHT 11
#define DHTTYPE DHT22 // DHT 22 (AM2302)
//#define DHTTYPE DHT21 // DHT 21 (AM2301)
// See guide for details on sensor wiring and usage:
// https://learn.adafruit.com/dht/overview
DHT_Unified dht(DHTPIN, DHTTYPE);
uint32_t delayMS;
void setup() {
Serial.begin(9600);
// Initialize device.
dht.begin();
Serial.println(F("DHTxx Unified Sensor Example"));
// Print temperature sensor details.
sensor_t sensor;
dht.temperature().getSensor(&sensor);
Serial.println(F("------------------------------------"));
Serial.println(F("Temperature Sensor"));
Serial.print (F("Sensor Type: ")); Serial.println(sensor.name);
Serial.print (F("Driver Ver: ")); Serial.println(sensor.version);
Serial.print (F("Unique ID: ")); Serial.println(sensor.sensor_id);
Serial.print (F("Max Value: ")); Serial.print(sensor.max_value); Serial.println(F("°C"));
Serial.print (F("Min Value: ")); Serial.print(sensor.min_value); Serial.println(F("°C"));
Serial.print (F("Resolution: ")); Serial.print(sensor.resolution); Serial.println(F("°C"));
Serial.println(F("------------------------------------"));
// Print humidity sensor details.
dht.humidity().getSensor(&sensor);
Serial.println(F("Humidity Sensor"));
Serial.print (F("Sensor Type: ")); Serial.println(sensor.name);
Serial.print (F("Driver Ver: ")); Serial.println(sensor.version);
Serial.print (F("Unique ID: ")); Serial.println(sensor.sensor_id);
Serial.print (F("Max Value: ")); Serial.print(sensor.max_value); Serial.println(F("%"));
Serial.print (F("Min Value: ")); Serial.print(sensor.min_value); Serial.println(F("%"));
Serial.print (F("Resolution: ")); Serial.print(sensor.resolution); Serial.println(F("%"));
Serial.println(F("------------------------------------"));
// Set delay between sensor readings based on sensor details.
delayMS = sensor.min_delay / 1000;
}
void loop() {
// Delay between measurements.
delay(delayMS);
// Get temperature event and print its value.
sensors_event_t event;
dht.temperature().getEvent(&event);
if (isnan(event.temperature)) {
Serial.println(F("Error reading temperature!"));
}
else {
Serial.print(F("Temperature: "));
Serial.print(event.temperature);
Serial.println(F("°C"));
}
// Get humidity event and print its value.
dht.humidity().getEvent(&event);
if (isnan(event.relative_humidity)) {
Serial.println(F("Error reading humidity!"));
}
else {
Serial.print(F("Humidity: "));
Serial.print(event.relative_humidity);
Serial.println(F("%"));
}
}

View file

@ -1,74 +0,0 @@
// Example testing sketch for various DHT humidity/temperature sensors
// Written by ladyada, public domain
// REQUIRES the following Arduino libraries:
// - DHT Sensor Library: https://github.com/adafruit/DHT-sensor-library
// - Adafruit Unified Sensor Lib: https://github.com/adafruit/Adafruit_Sensor
#include "DHT.h"
#define DHTPIN 2 // Digital pin connected to the DHT sensor
// Feather HUZZAH ESP8266 note: use pins 3, 4, 5, 12, 13 or 14 --
// Pin 15 can work but DHT must be disconnected during program upload.
// Uncomment whatever type you're using!
//#define DHTTYPE DHT11 // DHT 11
#define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321
//#define DHTTYPE DHT21 // DHT 21 (AM2301)
// Connect pin 1 (on the left) of the sensor to +5V
// NOTE: If using a board with 3.3V logic like an Arduino Due connect pin 1
// to 3.3V instead of 5V!
// Connect pin 2 of the sensor to whatever your DHTPIN is
// Connect pin 3 (on the right) of the sensor to GROUND (if your sensor has 3 pins)
// Connect pin 4 (on the right) of the sensor to GROUND and leave the pin 3 EMPTY (if your sensor has 4 pins)
// Connect a 10K resistor from pin 2 (data) to pin 1 (power) of the sensor
// Initialize DHT sensor.
// Note that older versions of this library took an optional third parameter to
// tweak the timings for faster processors. This parameter is no longer needed
// as the current DHT reading algorithm adjusts itself to work on faster procs.
DHT dht(DHTPIN, DHTTYPE);
void setup() {
Serial.begin(9600);
Serial.println(F("DHTxx test!"));
dht.begin();
}
void loop() {
// Wait a few seconds between measurements.
delay(2000);
// Reading temperature or humidity takes about 250 milliseconds!
// Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
float h = dht.readHumidity();
// Read temperature as Celsius (the default)
float t = dht.readTemperature();
// Read temperature as Fahrenheit (isFahrenheit = true)
float f = dht.readTemperature(true);
// Check if any reads failed and exit early (to try again).
if (isnan(h) || isnan(t) || isnan(f)) {
Serial.println(F("Failed to read from DHT sensor!"));
return;
}
// Compute heat index in Fahrenheit (the default)
float hif = dht.computeHeatIndex(f, h);
// Compute heat index in Celsius (isFahreheit = false)
float hic = dht.computeHeatIndex(t, h, false);
Serial.print(F("Humidity: "));
Serial.print(h);
Serial.print(F("% Temperature: "));
Serial.print(t);
Serial.print(F("°C "));
Serial.print(f);
Serial.print(F("°F Heat index: "));
Serial.print(hic);
Serial.print(F("°C "));
Serial.print(hif);
Serial.println(F("°F"));
}

View file

@ -1,22 +0,0 @@
###########################################
# Syntax Coloring Map For DHT-sensor-library
###########################################
###########################################
# Datatypes (KEYWORD1)
###########################################
DHT KEYWORD1
###########################################
# Methods and Functions (KEYWORD2)
###########################################
begin KEYWORD2
readTemperature KEYWORD2
convertCtoF KEYWORD2
convertFtoC KEYWORD2
computeHeatIndex KEYWORD2
readHumidity KEYWORD2
read KEYWORD2

View file

@ -1,10 +0,0 @@
name=DHT sensor library
version=1.4.4
author=Adafruit
maintainer=Adafruit <info@adafruit.com>
sentence=Arduino library for DHT11, DHT22, etc Temp & Humidity Sensors
paragraph=Arduino library for DHT11, DHT22, etc Temp & Humidity Sensors
category=Sensors
url=https://github.com/adafruit/DHT-sensor-library
architectures=*
depends=Adafruit Unified Sensor

View file

@ -1,20 +0,0 @@
Copyright (c) 2020 Adafruit Industries
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
OR OTHER DEALINGS IN THE SOFTWARE.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

101
Dht11/dht11.cpp Normal file
View file

@ -0,0 +1,101 @@
//
// FILE: dht11.cpp
// VERSION: 0.4.1
// PURPOSE: DHT11 Temperature & Humidity Sensor library for Arduino
// LICENSE: GPL v3 (http://www.gnu.org/licenses/gpl.html)
//
// DATASHEET: http://www.micro4you.com/files/sensor/DHT11.pdf
//
// HISTORY:
// George Hadjikyriacou - Original version (??)
// Mod by SimKard - Version 0.2 (24/11/2010)
// Mod by Rob Tillaart - Version 0.3 (28/03/2011)
// + added comments
// + removed all non DHT11 specific code
// + added references
// Mod by Rob Tillaart - Version 0.4 (17/03/2012)
// + added 1.0 support
// Mod by Rob Tillaart - Version 0.4.1 (19/05/2012)
// + added error codes
//
#include "dht11.h"
// Return values:
// DHTLIB_OK
// DHTLIB_ERROR_CHECKSUM
// DHTLIB_ERROR_TIMEOUT
int dht11::read(int pin)
{
// BUFFER TO RECEIVE
uint8_t bits[5]={0,0,0,0,0};
uint8_t cnt = 7;
uint8_t idx = 0;
// EMPTY BUFFER
for (int i=0; i< 5; i++) bits[i] = 0;
// REQUEST SAMPLE
pinMode(pin, OUTPUT);
digitalWrite(pin, LOW);
delay(20);
digitalWrite(pin, HIGH);
delayMicroseconds(40);
pinMode(pin, INPUT);
// ACKNOWLEDGE or TIMEOUT
unsigned int loopCnt = 80;
while(digitalRead(pin) == LOW)
{
delayMicroseconds(1);
if (loopCnt-- == 0) return DHTLIB_ERROR_TIMEOUT;
}
loopCnt = 80;
while(digitalRead(pin) == HIGH)
{
delayMicroseconds(1);
if (loopCnt-- == 0) return DHTLIB_ERROR_TIMEOUT;
}
// READ OUTPUT - 40 BITS => 5 BYTES or TIMEOUT
for (int i=0; i<40; i++)
{
loopCnt = 10000;
while(digitalRead(pin) == LOW)
if (loopCnt-- == 0) return DHTLIB_ERROR_TIMEOUT;
unsigned long t = micros();
loopCnt = 10000;
while(digitalRead(pin) == HIGH)
if (loopCnt-- == 0) return DHTLIB_ERROR_TIMEOUT;
if ((micros() - t) > 40) bits[idx] |= (1 << cnt);
if (cnt == 0) // next byte?
{
cnt = 7; // restart at MSB
idx++; // next byte!
}
else cnt--;
}
// WRITE TO RIGHT VARS
// as bits[1] and bits[3] are allways zero they are omitted in formulas.
humidity = bits[0];
temperature = bits[2];
byt0=bits[0];
byt1=bits[1];
byt2=bits[2];
byt3=bits[3];
byt4=bits[4];
uint8_t sum = bits[0] + bits[1]+bits[2]+bits[3];
if (bits[4] != sum) return DHTLIB_ERROR_CHECKSUM;
return DHTLIB_OK;
}
//
// END OF FILE
//

33
Dht11/dht11.h Normal file
View file

@ -0,0 +1,33 @@
#ifndef dht11_h
#define dht11_h
#if defined(ARDUINO) && (ARDUINO >= 100)
#include <Arduino.h>
#else
#include <WProgram.h>
#endif
#define DHT11LIB_VERSION "0.4.1"
#define DHTLIB_OK 0
#define DHTLIB_ERROR_CHECKSUM -1
#define DHTLIB_ERROR_TIMEOUT -2
class dht11
{
public:
int read(int pin);
int humidity;
int temperature;
int byt0;
int byt1;
int byt2;
int byt3;
int byt4;
};
#endif
//
// END OF FILE
//

View file

@ -0,0 +1,94 @@
double Fahrenheit(double celsius)
{
return 1.8 * celsius + 32;
} //摄氏温度度转化为华氏温度
double Kelvin(double celsius)
{
return celsius + 273.15;
} //摄氏温度转化为开氏温度
// 露点(点在此温度时,空气饱和并产生露珠)
// 参考: http://wahiduddin.net/calc/density_algorithms.htm
double dewPoint(double celsius, double humidity)
{
double A0= 373.15/(273.15 + celsius);
double SUM = -7.90298 * (A0-1);
SUM += 5.02808 * log10(A0);
SUM += -1.3816e-7 * (pow(10, (11.344*(1-1/A0)))-1) ;
SUM += 8.1328e-3 * (pow(10,(-3.49149*(A0-1)))-1) ;
SUM += log10(1013.246);
double VP = pow(10, SUM-3) * humidity;
double T = log(VP/0.61078); // temp var
return (241.88 * T) / (17.558-T);
}
// 快速计算露点速度是5倍dewPoint()
// 参考: http://en.wikipedia.org/wiki/Dew_point
double dewPointFast(double celsius, double humidity)
{
double a = 17.271;
double b = 237.7;
double temp = (a * celsius) / (b + celsius) + log(humidity/100);
double Td = (b * temp) / (a - temp);
return Td;
}
#include <dht11.h>
dht11 DHT11;
#define DHT11PIN 2
void setup()
{
Serial.begin(9600);
Serial.println("DHT11 TEST PROGRAM ");
Serial.print("LIBRARY VERSION: ");
Serial.println(DHT11LIB_VERSION);
Serial.println();
}
void loop()
{
Serial.println("\n");
int chk = DHT11.read(DHT11PIN);
Serial.print("Read sensor: ");
switch (chk)
{
case DHTLIB_OK:
Serial.println("OK");
break;
case DHTLIB_ERROR_CHECKSUM:
Serial.println("Checksum error");
break;
case DHTLIB_ERROR_TIMEOUT:
Serial.println("Time out error");
break;
default:
Serial.println("Unknown error");
break;
}
Serial.print("Humidity (%): ");
Serial.println((float)DHT11.humidity, 2);
Serial.print("Temperature (oC): ");
Serial.println((float)DHT11.temperature, 2);
Serial.print("Temperature (oF): ");
Serial.println(Fahrenheit(DHT11.temperature), 2);
Serial.print("Temperature (K): ");
Serial.println(Kelvin(DHT11.temperature), 2);
Serial.print("Dew Point (oC): ");
Serial.println(dewPoint(DHT11.temperature, DHT11.humidity));
Serial.print("Dew PointFast (oC): ");
Serial.println(dewPointFast(DHT11.temperature, DHT11.humidity));
delay(2000);
}

View file

@ -1,13 +0,0 @@
# Contribution Guidelines
This library is the culmination of the expertise of many members of the open source community who have dedicated their time and hard work. The best way to ask for help or propose a new idea is to [create a new issue](https://github.com/winlinvip/SimpleDHT/issues/new) while creating a Pull Request with your code changes allows you to share your own innovations with the rest of the community.
The following are some guidelines to observe when creating issues or PRs:
- Be friendly; it is important that we can all enjoy a safe space as we are all working on the same project and it is okay for people to have different ideas
- [Use code blocks](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet#code); it helps us help you when we can read your code! On that note also refrain from pasting more than 30 lines of code in a post, instead [create a gist](https://gist.github.com/) if you need to share large snippets
- Use reasonable titles; refrain from using overly long or capitalized titles as they are usually annoying and do little to encourage others to help :smile:
- Be detailed; refrain from mentioning code problems without sharing your source code and always give information regarding your board and version of the library.

View file

@ -1,21 +0,0 @@
The MIT License (MIT)
Copyright (c) 2016-2017 winlin
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View file

@ -1,182 +0,0 @@
# SimpleDHT
## Description
An Arduino library for the DHT series of low-cost temperature/humidity sensors.
You can find DHT11 and DHT22 tutorials [here](https://learn.adafruit.com/dht).
## Installation
### First Method
![image](https://user-images.githubusercontent.com/36513474/68069796-09e62200-fd87-11e9-81e0-dc75e38efed0.png)
1. In the Arduino IDE, navigate to Sketch > Include Library > Manage Libraries
1. Then the Library Manager will open and you will find a list of libraries that are already installed or ready for installation.
1. Then search for SimpleDHT using the search bar.
1. Click on the text area and then select the specific version and install it.
### Second Method
1. Navigate to the [Releases page](https://github.com/winlinvip/SimpleDHT/releases).
1. Download the latest release.
1. Extract the zip file
1. In the Arduino IDE, navigate to Sketch > Include Library > Add .ZIP Library
## Usage
To use this library:
1. Open example: Arduino => File => Examples => SimpleDHT => DHT11Default
1. Connect the DHT11 and upload the program to Arduino.
1. Open the Serial Window of Arduino IDE, we got the result as follows.
```Cpp
=================================
Sample DHT11...
Sample OK: 19 *C, 31 H
=================================
Sample DHT11...
Sample OK: 19 *C, 31 H
=================================
```
> Remark: For DHT11, no more than 1 Hz sampling rate (once every second).
> Remark: For DHT22, no more than 0.5 Hz sampling rate (once every 2 seconds).
## Features
- ### Simple
Simple C++ code with lots of comments.
- ### Stable
Strictly follow the standard DHT protocol.
- ### Fast
Support 0.5HZ(DHT22) or 1HZ(DHT11) sampling rate.
- ### Compatible
SimpleDHT sensor library is compatible with multiple low-cost temperatures and humidity sensors like DHT11 and DHT22. A few examples are implemented just to demonstrate how to modify the code for different sensors.
- ### MIT License
DHT sensor library is open-source and uses one of the most permissive licenses so you can use it on any project.
- Commercial use
- Modification
- Distribution
- Private use
## Functions
- read()
- setPinInputMode()
- setPin()
- getBitmask()
- getPort()
- levelTime()
- bits2byte()
- parse()
- read2()
- sample()
## Sensors
- [x] DHT11, The [product](https://www.adafruit.com/product/386), [datasheet](https://akizukidenshi.com/download/ds/aosong/DHT11.pdf) and [example](https://github.com/winlinvip/SimpleDHT/tree/master/examples/DHT11Default), 1HZ sampling rate.
- [x] DHT22, The [product](https://www.adafruit.com/product/385), [datasheet](http://akizukidenshi.com/download/ds/aosong/AM2302.pdf) and [example](https://github.com/winlinvip/SimpleDHT/tree/master/examples/DHT22Default), 0.5Hz sampling rate.
## Examples
This library including the following examples:
1. [DHT11Default](https://github.com/winlinvip/SimpleDHT/tree/master/examples/DHT11Default): Use DHT11 to sample.
1. [DHT11WithRawBits](https://github.com/winlinvip/SimpleDHT/tree/master/examples/DHT11WithRawBits): Use DHT11 to sample and get the 40bits RAW data.
1. [DHT11ErrCount](https://github.com/winlinvip/SimpleDHT/tree/master/examples/DHT11ErrCount): Use DHT11 to sample and stat the success rate.
1. [DHT22Default](https://github.com/winlinvip/SimpleDHT/tree/master/examples/DHT22Default): Use DHT22 to sample.
1. [DHT22WithRawBits](https://github.com/winlinvip/SimpleDHT/tree/master/examples/DHT22WithRawBits): Use DHT22 to sample and get the 40bits RAW data.
1. [DHT22Integer](https://github.com/winlinvip/SimpleDHT/tree/master/examples/DHT22Integer): Use DHT22 to sample and ignore the fractional data.
1. [DHT22ErrCount](https://github.com/winlinvip/SimpleDHT/tree/master/examples/DHT22ErrCount): Use DHT22 to sample and stat the success rate.
1. [TwoSensorsDefault](https://github.com/winlinvip/SimpleDHT/tree/master/examples/TwoSensorsDefault): Use two DHT11 to sample.
One of the SimpleDHT examples is the following:
- ### DHT22Integer
```Cpp
#include <SimpleDHT.h>
int pinDHT22 = 2;
SimpleDHT22 dht22(pinDHT22);
void setup() {
Serial.begin(115200);
}
void loop() {
Serial.println("=================================");
Serial.println("Sample DHT22...");
byte temperature = 0;
byte humidity = 0;
int err = SimpleDHTErrSuccess;
if ((err = dht22.read(&temperature, &humidity, NULL)) != SimpleDHTErrSuccess) {
Serial.print("Read DHT22 failed, err="); Serial.print(SimpleDHTErrCode(err));
Serial.print(","); Serial.println(SimpleDHTErrDuration(err)); delay(2000);
return;
}
Serial.print("Sample OK: ");
Serial.print((int)temperature); Serial.print(" *C, ");
Serial.print((int)humidity); Serial.println(" RH%");
delay(2500);
}
```
## Links
1. [adafruit/DHT-sensor-library](https://github.com/adafruit/DHT-sensor-library)
1. [Arduino #4469: Add SimpleDHT library.](https://github.com/arduino/Arduino/issues/4469)
1. [DHT11 datasheet and protocol.](https://akizukidenshi.com/download/ds/aosong/DHT11.pdf)
1. [DHT22 datasheet and protoocl.](http://akizukidenshi.com/download/ds/aosong/AM2302.pdf)
Winlin 2016.1
## Contributing
If you want to contribute to this project:
- Report bugs and errors
- Ask for enhancements
- Create issues and pull requests
- Tell others about this library
- Contribute new protocols
Please read [CONTRIBUTING.md](https://github.com/winlinvip/SimpleDHT/blob/master/CONTRIBUTING.md) for details on our code of conduct, and the process for submitting pull requests to us.
## Credits
The author and maintainer of this library is Winlin <winlin@vip.126.com>.
Based on previous work by:
- t-w
- O. Santos
- P. H. Dabrowski
- per1234
- P. Rinn
- G. M. Vacondio
- D. Faust
- C. Stroie
- Samlof
- Agha Saad Fraz
## License
This library is licensed under [MIT](https://github.com/winlinvip/SimpleDHT/blob/master/LICENSE).

View file

@ -1,364 +0,0 @@
/*
The MIT License (MIT)
Copyright (c) 2016-2017 winlin
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include "SimpleDHT.h"
SimpleDHT::SimpleDHT() {
}
SimpleDHT::SimpleDHT(int pin) {
setPin(pin);
}
void SimpleDHT::setPin(int pin) {
this->pin = pin;
#ifdef __AVR
// (only AVR) - set low level properties for configured pin
bitmask = digitalPinToBitMask(pin);
port = digitalPinToPort(pin);
#endif
}
int SimpleDHT::setPinInputMode(uint8_t mode) {
if (mode != INPUT && mode != INPUT_PULLUP) {
return SimpleDHTErrPinMode;
}
this->pinInputMode = mode;
return SimpleDHTErrSuccess;
}
int SimpleDHT::read(byte* ptemperature, byte* phumidity, byte pdata[40]) {
int ret = SimpleDHTErrSuccess;
if (pin == -1) {
return SimpleDHTErrNoPin;
}
float temperature = 0;
float humidity = 0;
if ((ret = read2(&temperature, &humidity, pdata)) != SimpleDHTErrSuccess) {
return ret;
}
if (ptemperature) {
*ptemperature = (byte)(int)temperature;
}
if (phumidity) {
*phumidity = (byte)(int)humidity;
}
return ret;
}
int SimpleDHT::read(int pin, byte* ptemperature, byte* phumidity, byte pdata[40]) {
setPin(pin);
return read(ptemperature, phumidity, pdata);
}
#ifdef __AVR
int SimpleDHT::getBitmask() {
return bitmask;
}
int SimpleDHT::getPort() {
return port;
}
#endif
long SimpleDHT::levelTime(byte level, int firstWait, int interval) {
unsigned long time_start = micros();
long time = 0;
#ifdef __AVR
uint8_t portState = level ? bitmask : 0;
#endif
bool loop = true;
for (int i = 0 ; loop; i++) {
if (time < 0 || time > levelTimeout) {
return -1;
}
if (i == 0) {
if (firstWait > 0) {
delayMicroseconds(firstWait);
}
} else if (interval > 0) {
delayMicroseconds(interval);
}
// for an unsigned int type, the difference have a correct value
// even if overflow, explanation here:
// https://arduino.stackexchange.com/questions/33572/arduino-countdown-without-using-delay
time = micros() - time_start;
#ifdef __AVR
loop = ((*portInputRegister(port) & bitmask) == portState);
#else
loop = (digitalRead(pin) == level);
#endif
}
return time;
}
byte SimpleDHT::bits2byte(byte data[8]) {
byte v = 0;
for (int i = 0; i < 8; i++) {
v += data[i] << (7 - i);
}
return v;
}
int SimpleDHT::parse(byte data[40], short* ptemperature, short* phumidity) {
short humidity = bits2byte(data);
short humidity2 = bits2byte(data + 8);
short temperature = bits2byte(data + 16);
short temperature2 = bits2byte(data + 24);
byte check = bits2byte(data + 32);
byte expect = (byte)humidity + (byte)humidity2 + (byte)temperature + (byte)temperature2;
if (check != expect) {
return SimpleDHTErrDataChecksum;
}
*ptemperature = temperature<<8 | temperature2;
*phumidity = humidity<<8 | humidity2;
return SimpleDHTErrSuccess;
}
SimpleDHT11::SimpleDHT11() {
}
SimpleDHT11::SimpleDHT11(int pin) : SimpleDHT (pin) {
}
int SimpleDHT11::read2(float* ptemperature, float* phumidity, byte pdata[40]) {
int ret = SimpleDHTErrSuccess;
if (pin == -1) {
return SimpleDHTErrNoPin;
}
byte data[40] = {0};
if ((ret = sample(data)) != SimpleDHTErrSuccess) {
return ret;
}
short temperature = 0;
short humidity = 0;
if ((ret = parse(data, &temperature, &humidity)) != SimpleDHTErrSuccess) {
return ret;
}
if (pdata) {
memcpy(pdata, data, 40);
}
if (ptemperature) {
*ptemperature = (int)(temperature>>8);
}
if (phumidity) {
*phumidity = (int)(humidity>>8);
}
// For example, when remove the data line, it will be success with zero data.
if (temperature == 0 && humidity == 0) {
return SimpleDHTErrZeroSamples;
}
return ret;
}
int SimpleDHT11::read2(int pin, float* ptemperature, float* phumidity, byte pdata[40]) {
setPin(pin);
return read2(ptemperature, phumidity, pdata);
}
int SimpleDHT11::sample(byte data[40]) {
// empty output data.
memset(data, 0, 40);
// According to protocol: [1] https://akizukidenshi.com/download/ds/aosong/DHT11.pdf
// notify DHT11 to start:
// 1. PULL LOW 20ms.
// 2. PULL HIGH 20-40us.
// 3. SET TO INPUT or INPUT_PULLUP.
// Changes in timing done according to:
// [2] https://www.mouser.com/ds/2/758/DHT11-Technical-Data-Sheet-Translated-Version-1143054.pdf
// - original values specified in code
// - since they were not working (MCU-dependent timing?), replace in code with
// _working_ values based on measurements done with levelTimePrecise()
pinMode(pin, OUTPUT);
digitalWrite(pin, LOW); // 1.
delay(20); // specs [2]: 18us
// Pull high and set to input, before wait 40us.
// @see https://github.com/winlinvip/SimpleDHT/issues/4
// @see https://github.com/winlinvip/SimpleDHT/pull/5
digitalWrite(pin, HIGH); // 2.
pinMode(pin, this->pinInputMode);
delayMicroseconds(25); // specs [2]: 20-40us
// DHT11 starting:
// 1. PULL LOW 80us
// 2. PULL HIGH 80us
long t = levelTime(LOW); // 1.
if (t < 30) { // specs [2]: 80us
return simpleDHTCombileError(t, SimpleDHTErrStartLow);
}
t = levelTime(HIGH); // 2.
if (t < 50) { // specs [2]: 80us
return simpleDHTCombileError(t, SimpleDHTErrStartHigh);
}
// DHT11 data transmite:
// 1. 1bit start, PULL LOW 50us
// 2. PULL HIGH:
// - 26-28us, bit(0)
// - 70us, bit(1)
for (int j = 0; j < 40; j++) {
t = levelTime(LOW); // 1.
if (t < 24) { // specs says: 50us
return simpleDHTCombileError(t, SimpleDHTErrDataLow);
}
// read a bit
t = levelTime(HIGH); // 2.
if (t < 11) { // specs say: 20us
return simpleDHTCombileError(t, SimpleDHTErrDataRead);
}
data[ j ] = (t > 40 ? 1 : 0); // specs: 26-28us -> 0, 70us -> 1
}
// DHT11 EOF:
// 1. PULL LOW 50us.
t = levelTime(LOW); // 1.
if (t < 24) { // specs say: 50us
return simpleDHTCombileError(t, SimpleDHTErrDataEOF);
}
return SimpleDHTErrSuccess;
}
SimpleDHT22::SimpleDHT22() {
}
SimpleDHT22::SimpleDHT22(int pin) : SimpleDHT (pin) {
}
int SimpleDHT22::read2(float* ptemperature, float* phumidity, byte pdata[40]) {
int ret = SimpleDHTErrSuccess;
if (pin == -1) {
return SimpleDHTErrNoPin;
}
byte data[40] = {0};
if ((ret = sample(data)) != SimpleDHTErrSuccess) {
return ret;
}
short temperature = 0;
short humidity = 0;
if ((ret = parse(data, &temperature, &humidity)) != SimpleDHTErrSuccess) {
return ret;
}
if (pdata) {
memcpy(pdata, data, 40);
}
if (ptemperature) {
*ptemperature = (float)((temperature & 0x8000 ? -1 : 1) * (temperature & 0x7FFF)) / 10.0;
}
if (phumidity) {
*phumidity = (float)humidity / 10.0;
}
return ret;
}
int SimpleDHT22::read2(int pin, float* ptemperature, float* phumidity, byte pdata[40]) {
setPin(pin);
return read2(ptemperature, phumidity, pdata);
}
int SimpleDHT22::sample(byte data[40]) {
// empty output data.
memset(data, 0, 40);
// According to protocol: http://akizukidenshi.com/download/ds/aosong/AM2302.pdf
// notify DHT22 to start:
// 1. T(be), PULL LOW 1ms(0.8-20ms).
// 2. T(go), PULL HIGH 30us(20-200us), use 40us.
// 3. SET TO INPUT or INPUT_PULLUP.
pinMode(pin, OUTPUT);
digitalWrite(pin, LOW);
delayMicroseconds(1000);
// Pull high and set to input, before wait 40us.
// @see https://github.com/winlinvip/SimpleDHT/issues/4
// @see https://github.com/winlinvip/SimpleDHT/pull/5
digitalWrite(pin, HIGH);
pinMode(pin, this->pinInputMode);
delayMicroseconds(40);
// DHT22 starting:
// 1. T(rel), PULL LOW 80us(75-85us).
// 2. T(reh), PULL HIGH 80us(75-85us).
long t = 0;
if ((t = levelTime(LOW)) < 30) {
return simpleDHTCombileError(t, SimpleDHTErrStartLow);
}
if ((t = levelTime(HIGH)) < 50) {
return simpleDHTCombileError(t, SimpleDHTErrStartHigh);
}
// DHT22 data transmite:
// 1. T(LOW), 1bit start, PULL LOW 50us(48-55us).
// 2. T(H0), PULL HIGH 26us(22-30us), bit(0)
// 3. T(H1), PULL HIGH 70us(68-75us), bit(1)
for (int j = 0; j < 40; j++) {
t = levelTime(LOW); // 1.
if (t < 24) { // specs says: 50us
return simpleDHTCombileError(t, SimpleDHTErrDataLow);
}
// read a bit
t = levelTime(HIGH); // 2.
if (t < 11) { // specs say: 26us
return simpleDHTCombileError(t, SimpleDHTErrDataRead);
}
data[ j ] = (t > 40 ? 1 : 0); // specs: 22-30us -> 0, 70us -> 1
}
// DHT22 EOF:
// 1. T(en), PULL LOW 50us(45-55us).
t = levelTime(LOW);
if (t < 24) {
return simpleDHTCombileError(t, SimpleDHTErrDataEOF);
}
return SimpleDHTErrSuccess;
}

View file

@ -1,189 +0,0 @@
/*
The MIT License (MIT)
Copyright (c) 2016-2017 winlin
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#ifndef __SIMPLE_DHT_H
#define __SIMPLE_DHT_H
#include <Arduino.h>
// High 8bits are time duration.
// Low 8bits are error code.
// For example, 0x0310 means t=0x03 and code=0x10,
// which is start low signal(0x10) error.
// @see https://github.com/winlinvip/SimpleDHT/issues/25
#define simpleDHTCombileError(t, err) ((t << 8) & 0xff00) | (err & 0x00ff)
// Get the time duration from error.
#define SimpleDHTErrDuration(err) ((err&0xff00)>>8)
// Get the error code defined bellow.
#define SimpleDHTErrCode(err) (err&0x00ff)
// Success.
#define SimpleDHTErrSuccess 0
// Error to wait for start low signal.
#define SimpleDHTErrStartLow 16
// Error to wait for start high signal.
#define SimpleDHTErrStartHigh 17
// Error to wait for data start low signal.
#define SimpleDHTErrDataLow 18
// Error to wait for data read signal.
#define SimpleDHTErrDataRead 19
// Error to wait for data EOF signal.
#define SimpleDHTErrDataEOF 20
// Error to validate the checksum.
#define SimpleDHTErrDataChecksum 21
// Error when temperature and humidity are zero, it shouldn't happen.
#define SimpleDHTErrZeroSamples 22
// Error when pin is not initialized.
#define SimpleDHTErrNoPin 23
// Error when pin mode is invalid.
#define SimpleDHTErrPinMode 24
class SimpleDHT {
protected:
long levelTimeout = 500000; // 500ms
int pin = -1;
uint8_t pinInputMode = INPUT;
#ifdef __AVR
// For direct GPIO access (8-bit AVRs only), store port and bitmask
// of the digital pin connected to the DHT.
// (other platforms use digitalRead(), do not need this)
uint8_t bitmask = 0xFF;
uint8_t port = 0xFF;
#endif
public:
SimpleDHT();
SimpleDHT(int pin);
public:
// To (eventually) change the pin configuration for existing instance
// @param pin The DHT11 or DHT22 pin.
virtual void setPin(int pin);
// Set the input mode of the pin from INPUT and INPUT_PULLUP
// to permit the use of the internal pullup resistor for
// for bare modules
// @param mode the pin input mode.
// @return SimpleDHTErrSuccess is success; otherwise, failed.
virtual int setPinInputMode(uint8_t mode);
public:
// Read from dht11 or dht22.
// @param pin The DHT11 pin.
// @param ptemperature output, NULL to igore. In Celsius.
// @param phumidity output, NULL to ignore.
// For DHT11, in H, such as 35H.
// For DHT22, in RH%, such as 53%RH.
// @param pdata output 40bits sample, NULL to ignore.
// @remark the min delay for this method is 1s(DHT11) or 2s(DHT22).
// @return SimpleDHTErrSuccess is success; otherwise, failed.
virtual int read(byte* ptemperature, byte* phumidity, byte pdata[40]);
virtual int read(int pin, byte* ptemperature, byte* phumidity, byte pdata[40]);
// To get a more accurate data.
// @remark it's available for dht22. for dht11, it's the same of read().
virtual int read2(float* ptemperature, float* phumidity, byte pdata[40]) = 0;
virtual int read2(int pin, float* ptemperature, float* phumidity, byte pdata[40]) = 0;
protected:
// For only AVR - methods returning low level conf. of the pin
#ifdef __AVR
// @return Bitmask to access pin state from port input register
virtual int getBitmask();
// @return Bitmask to access pin state from port input register
virtual int getPort();
#endif
protected:
// Measure and return time (in microseconds)
// with precision defined by interval between checking the state
// while pin is in specified state (HIGH or LOW)
// @param level state which time is measured.
// @param interval time interval between consecutive state checks.
// @return measured time (microseconds). -1 if timeout.
virtual long levelTime(byte level, int firstWait = 10, int interval = 6);
// @data the bits of a byte.
// @remark please use simple_dht11_read().
virtual byte bits2byte(byte data[8]);
// read temperature and humidity from dht11.
// @param data a byte[40] to read bits to 5bytes.
// @return 0 success; otherwise, error.
// @remark please use simple_dht11_read().
virtual int sample(byte data[40]) = 0;
// parse the 40bits data to temperature and humidity.
// @remark please use simple_dht11_read().
virtual int parse(byte data[40], short* ptemperature, short* phumidity);
};
/*
Simple DHT11
Simple, Stable and Fast DHT11 library.
The circuit:
* VCC: 5V or 3V
* GND: GND
* DATA: Digital ping, for instance 2.
23 Jan 2016 By winlin <winlin@vip.126.com>
https://github.com/winlinvip/SimpleDHT#usage
https://akizukidenshi.com/download/ds/aosong/DHT11.pdf
https://cdn-shop.adafruit.com/datasheets/DHT11-chinese.pdf
*/
class SimpleDHT11 : public SimpleDHT {
public:
SimpleDHT11();
SimpleDHT11(int pin);
public:
virtual int read2(float* ptemperature, float* phumidity, byte pdata[40]);
virtual int read2(int pin, float* ptemperature, float* phumidity, byte pdata[40]);
protected:
virtual int sample(byte data[40]);
};
/*
Simple DHT22
Simple, Stable and Fast DHT22 library.
The circuit:
* VCC: 5V or 3V
* GND: GND
* DATA: Digital ping, for instance 2.
3 Jun 2017 By winlin <winlin@vip.126.com>
https://github.com/winlinvip/SimpleDHT#usage
http://akizukidenshi.com/download/ds/aosong/AM2302.pdf
https://cdn-shop.adafruit.com/datasheets/DHT22.pdf
*/
class SimpleDHT22 : public SimpleDHT {
public:
SimpleDHT22();
SimpleDHT22(int pin);
public:
virtual int read2(float* ptemperature, float* phumidity, byte pdata[40]);
virtual int read2(int pin, float* ptemperature, float* phumidity, byte pdata[40]);
protected:
virtual int sample(byte data[40]);
};
#endif

View file

@ -1,35 +0,0 @@
#include <SimpleDHT.h>
// for DHT11,
// VCC: 5V or 3V
// GND: GND
// DATA: 2
int pinDHT11 = 2;
SimpleDHT11 dht11(pinDHT11);
void setup() {
Serial.begin(115200);
}
void loop() {
// start working...
Serial.println("=================================");
Serial.println("Sample DHT11...");
// read without samples.
byte temperature = 0;
byte humidity = 0;
int err = SimpleDHTErrSuccess;
if ((err = dht11.read(&temperature, &humidity, NULL)) != SimpleDHTErrSuccess) {
Serial.print("Read DHT11 failed, err="); Serial.print(SimpleDHTErrCode(err));
Serial.print(","); Serial.println(SimpleDHTErrDuration(err)); delay(1000);
return;
}
Serial.print("Sample OK: ");
Serial.print((int)temperature); Serial.print(" *C, ");
Serial.print((int)humidity); Serial.println(" H");
// DHT11 sampling rate is 1HZ.
delay(1500);
}

View file

@ -1,42 +0,0 @@
#include <SimpleDHT.h>
// for DHT11,
// VCC: 5V or 3V
// GND: GND
// DATA: 2
int pinDHT11 = 2;
SimpleDHT11 dht11(pinDHT11);
void setup() {
Serial.begin(115200);
}
void loop() {
// start working...
Serial.println("=================================");
Serial.println("Sample DHT11 with error count");
int cnt = 0;
int err_cnt = 0;
for (;;) {
cnt++;
byte temperature = 0;
byte humidity = 0;
int err = SimpleDHTErrSuccess;
if ((err = dht11.read(&temperature, &humidity, NULL)) != SimpleDHTErrSuccess) {
Serial.print("Read DHT11 failed, err="); Serial.print(SimpleDHTErrCode(err));
Serial.print(","); Serial.print(SimpleDHTErrDuration(err));
err_cnt++;
} else {
Serial.print("DHT11, ");
Serial.print((int)temperature); Serial.print(" *C, ");
Serial.print((int)humidity); Serial.print(" H");
}
Serial.print(", total: "); Serial.print(cnt);
Serial.print(", err: "); Serial.print(err_cnt);
Serial.print(", success rate: "); Serial.print((cnt - err_cnt) * 100.0 / (float)cnt); Serial.println("%");
delay(1500);
}
}

View file

@ -1,45 +0,0 @@
#include <SimpleDHT.h>
// for DHT11,
// VCC: 5V or 3V
// GND: GND
// DATA: 2
int pinDHT11 = 2;
SimpleDHT11 dht11(pinDHT11);
void setup() {
Serial.begin(115200);
}
void loop() {
// start working...
Serial.println("=================================");
Serial.println("Sample DHT11 with RAW bits...");
// read with raw sample data.
byte temperature = 0;
byte humidity = 0;
byte data[40] = {0};
int err = SimpleDHTErrSuccess;
if ((err = dht11.read(&temperature, &humidity, data)) != SimpleDHTErrSuccess) {
Serial.print("Read DHT11 failed, err="); Serial.print(SimpleDHTErrCode(err));
Serial.print(","); Serial.println(SimpleDHTErrDuration(err)); delay(1000);
return;
}
Serial.print("Sample RAW Bits: ");
for (int i = 0; i < 40; i++) {
Serial.print((int)data[i]);
if (i > 0 && ((i + 1) % 4) == 0) {
Serial.print(' ');
}
}
Serial.println("");
Serial.print("Sample OK: ");
Serial.print((int)temperature); Serial.print(" *C, ");
Serial.print((int)humidity); Serial.println(" H");
// DHT11 sampling rate is 1HZ.
delay(1500);
}

View file

@ -1,37 +0,0 @@
#include <SimpleDHT.h>
// for DHT22,
// VCC: 5V or 3V
// GND: GND
// DATA: 2
int pinDHT22 = 2;
SimpleDHT22 dht22(pinDHT22);
void setup() {
Serial.begin(115200);
}
void loop() {
// start working...
Serial.println("=================================");
Serial.println("Sample DHT22...");
// read without samples.
// @remark We use read2 to get a float data, such as 10.1*C
// if user doesn't care about the accurate data, use read to get a byte data, such as 10*C.
float temperature = 0;
float humidity = 0;
int err = SimpleDHTErrSuccess;
if ((err = dht22.read2(&temperature, &humidity, NULL)) != SimpleDHTErrSuccess) {
Serial.print("Read DHT22 failed, err="); Serial.print(SimpleDHTErrCode(err));
Serial.print(","); Serial.println(SimpleDHTErrDuration(err)); delay(2000);
return;
}
Serial.print("Sample OK: ");
Serial.print((float)temperature); Serial.print(" *C, ");
Serial.print((float)humidity); Serial.println(" RH%");
// DHT22 sampling rate is 0.5HZ.
delay(2500);
}

View file

@ -1,42 +0,0 @@
#include <SimpleDHT.h>
// for DHT22,
// VCC: 5V or 3V
// GND: GND
// DATA: 2
int pinDHT22 = 2;
SimpleDHT22 dht22(pinDHT22);
void setup() {
Serial.begin(115200);
}
void loop() {
// start working...
Serial.println("=================================");
Serial.println("Sample DHT22 with error count");
int cnt = 0;
int err_cnt = 0;
for (;;) {
cnt++;
float temperature = 0;
float humidity = 0;
int err = SimpleDHTErrSuccess;
if ((err = dht22.read2(&temperature, &humidity, NULL)) != SimpleDHTErrSuccess) {
Serial.print("Read DHT22 failed, err="); Serial.print(SimpleDHTErrCode(err));
Serial.print(","); Serial.print(SimpleDHTErrDuration(err));
err_cnt++;
} else {
Serial.print("DHT22, ");
Serial.print((float)temperature); Serial.print(" *C, ");
Serial.print((float)humidity); Serial.print(" RH%");
}
Serial.print(", total: "); Serial.print(cnt);
Serial.print(", err: "); Serial.print(err_cnt);
Serial.print(", success rate: "); Serial.print((cnt - err_cnt) * 100.0 / (float)cnt); Serial.println("%");
delay(2500);
}
}

View file

@ -1,35 +0,0 @@
#include <SimpleDHT.h>
// for DHT22,
// VCC: 5V or 3V
// GND: GND
// DATA: 2
int pinDHT22 = 2;
SimpleDHT22 dht22(pinDHT22);
void setup() {
Serial.begin(115200);
}
void loop() {
// start working...
Serial.println("=================================");
Serial.println("Sample DHT22...");
// read without samples.
byte temperature = 0;
byte humidity = 0;
int err = SimpleDHTErrSuccess;
if ((err = dht22.read(&temperature, &humidity, NULL)) != SimpleDHTErrSuccess) {
Serial.print("Read DHT22 failed, err="); Serial.print(SimpleDHTErrCode(err));
Serial.print(","); Serial.println(SimpleDHTErrDuration(err)); delay(2000);
return;
}
Serial.print("Sample OK: ");
Serial.print((int)temperature); Serial.print(" *C, ");
Serial.print((int)humidity); Serial.println(" RH%");
// DHT22 sampling rate is 0.5HZ.
delay(2500);
}

View file

@ -1,47 +0,0 @@
#include <SimpleDHT.h>
// for DHT22,
// VCC: 5V or 3V
// GND: GND
// DATA: 2
int pinDHT22 = 2;
SimpleDHT22 dht22(pinDHT22);
void setup() {
Serial.begin(115200);
}
void loop() {
// start working...
Serial.println("=================================");
Serial.println("Sample DHT22 with RAW bits...");
// read with raw sample data.
// @remark We use read2 to get a float data, such as 10.1*C
// if user doesn't care about the accurate data, use read to get a byte data, such as 10*C.
float temperature = 0;
float humidity = 0;
byte data[40] = {0};
int err = SimpleDHTErrSuccess;
if ((err = dht22.read2(&temperature, &humidity, data)) != SimpleDHTErrSuccess) {
Serial.print("Read DHT22 failed, err="); Serial.print(SimpleDHTErrCode(err));
Serial.print(","); Serial.println(SimpleDHTErrDuration(err)); delay(2000);
return;
}
Serial.print("Sample RAW Bits: ");
for (int i = 0; i < 40; i++) {
Serial.print((int)data[i]);
if (i > 0 && ((i + 1) % 4) == 0) {
Serial.print(' ');
}
}
Serial.println("");
Serial.print("Sample OK: ");
Serial.print((float)temperature); Serial.print(" *C, ");
Serial.print((float)humidity); Serial.println(" RH%");
// DHT22 sampling rate is 0.5HZ.
delay(2500);
}

View file

@ -1,66 +0,0 @@
#include <SimpleDHT.h>
// Created by santosomar Ωr using SimpleDHT library to read data from two DHT11 sensors
// for DHT11,
// VCC: 5V or 3V
// GND: GND
// SENSOR 1 is in Digital Data pin: 2
// SENSOR 2 is in Digital Data pin: 4
int dataPinSensor1 = 2;
int dataPinSensor2 = 4;
SimpleDHT11 dht1(dataPinSensor1);
SimpleDHT11 dht2(dataPinSensor2);
void setup() {
Serial.begin(115200);
}
void loop() {
// Reading data from sensor 1...
Serial.println("=================================");
// Reading data from sensor 1...
Serial.println("Getting data from sensor 1...");
// read without samples.
byte temperature = 0;
byte humidity = 0;
int err = SimpleDHTErrSuccess;
if ((err = dht1.read(&temperature, &humidity, NULL)) != SimpleDHTErrSuccess) {
Serial.print("Read Sensor 1 failed, err="); Serial.print(SimpleDHTErrCode(err));
Serial.print(","); Serial.println(SimpleDHTErrDuration(err)); delay(1000);
return;
}
// converting Celsius to Fahrenheit
byte f = temperature * 1.8 + 32;
Serial.print("Sample OK: ");
Serial.print((int)temperature); Serial.print(" *C, ");
Serial.print((int)f); Serial.print(" *F, ");
Serial.print((int)humidity); Serial.println(" H humidity");
// Reading data from sensor 2...
// ============================
Serial.println("Getting data from sensor 2...");
byte temperature2 = 0;
byte humidity2 = 0;
if ((err = dht2.read(&temperature2, &humidity2, NULL)) != SimpleDHTErrSuccess) {
Serial.print("Read Sensor 2 failed, err="); Serial.print(SimpleDHTErrCode(err));
Serial.print(","); Serial.println(SimpleDHTErrDuration(err)); delay(1000);
return;
}
// converting Celsius to Fahrenheit
byte fb = temperature2 * 1.8 + 32;
Serial.print("Sample OK: ");
Serial.print((int)temperature2); Serial.print(" *C, ");
Serial.print((int)fb); Serial.print(" *F, ");
Serial.print((int)humidity2); Serial.println(" H humidity");
// DHT11 sampling rate is 1HZ.
delay(1500);
}

View file

@ -1,18 +0,0 @@
###########################################
# Syntax Coloring Map For SimpleDHT
###########################################
###########################################
# Datatypes (KEYWORD1)
###########################################
SimpleDHT11 KEYWORD1
SimpleDHT22 KEYWORD1
###########################################
# Methods and Functions (KEYWORD2)
###########################################
read KEYWORD2
###########################################
# Constants (LITERAL1)
###########################################

View file

@ -1,9 +0,0 @@
name=SimpleDHT
version=1.0.15
author=Winlin <winlin@vip.126.com>
maintainer=Winlin <winlin@vip.126.com>
sentence=Arduino Temp & Humidity Sensors for DHT11 and DHT22.
paragraph=Simple C++ code with lots of comments, strictly follow the standard DHT protocol, supports 0.5HZ(DHT22) or 1HZ(DHT11) sampling rate.
category=Sensors
url=https://github.com/winlinvip/SimpleDHT
architectures=*