Portal for car enthusiasts

Sensor in conjunction with arduino to measure air humidity and temperature. Connecting a DHT11 or DHT22 sensor to Arduino Arduino connecting a temperature and humidity sensor

The DHT11 and DHT22 sensors are very popular in the Arduino environment and are often used in weather station projects and. In this article, we will learn how you can use these sensors, how to properly connect to Arduino Uno, Mega or Nano boards, which libraries to use to write a sketch. These sensors do not stand out with special speed and accuracy, but they are easy to use, they can be safely used in your first projects due to their availability and low price.

The sensor consists of two parts - capacitive temperature sensor and a hygrometer. The first is used to measure temperature, the second - for humidity air. The chip inside can perform analog-to-digital conversion and output a digital signal that is read by the microcontroller.

In most cases, DHT11 or DHT22 is available in two versions: as a separate sensor in the form of a plastic case with metal contacts, or as a ready-made module with a sensor and soldered piping. The second option is much easier to use in real projects and highly recommended for beginners.

DHT11 sensor

  • Current consumption - 2.5 mA (maximum value during data conversion);
  • Measures humidity in the range from 20% to 80%. The error can be up to 5%;
  • It is used when measuring temperature in the range from 0 to 50 degrees (accuracy - 2%)
  • Dimensions: 15.5mm length; 12mm wide; 5.5mm height;
  • Power - from 3 to 5 Volts;
  • One measurement per unit of time (second). That is, the frequency is 1 Hz;
  • 4 connectors. Between adjacent distance of 0.1”.

  • Power - from 3 to 5 Volts;
  • The maximum current during conversion is 2.5 mA;
  • Able to measure humidity in the range from 0% to 100%. Measurement accuracy ranges from 2% to 5%;
  • The minimum measured temperature is minus 40, the maximum is 125 degrees Celsius (measurement accuracy - 0.5);
  • The device is capable of making one measurement in 2 seconds. Frequency - up to 0.5 Hz;
  • Dimensions: 15.1 mm length; 25 mm wide; 5.5mm height;
  • There are 4 connectors. Distance between adjacent - 0.1 ';

Obviously, when used in arduino temperature and humidity sensorDHT11 the device will give less accurate values ​​than the DHT22. The analogue has a larger range of measured values, but the price is appropriate. Temperature and Humidity SensorDHT22, like its counterpart, has one digital output, so you can take readings no more than once every 1-2 seconds.

Where to buy sensors at low prices

Traditionally, Aliexpress sellers offer the lowest prices. Here are the most interesting options:

Digital temperature and humidity sensors DHT11 DHT22 DHT22 as an Arduino Uno R3 compatible module Wireless DHT22 for weather stations based on WeMos - assembled like a sandwich
DHT22 Wireless Sensor Module (with ESP8266) An inexpensive version of the DHT11 temperature and humidity sensor is cheaper than 70 rubles! A well-executed DHT11 sensor from RobotDyn

Connecting DHT11 to Arduino Uno

If you only have the sensor itself on hand (a blue “grid” plastic box with 4 metal contacts), then to connect the DHT11 you will need the following parts:

    • Arduino board (or other microcontroller that supports microsecond timing);
    • Mounting (breadboard);
    • Pull-up resistor with a nominal value of 10 kOhm;
    • LEDs.

    DHT11 pin description:

    • Nutrition;
    • Data output;
    • Not used;
    • Ground (GND).

    The contacts are numbered from left to right, if the sensor body is in front of you from the side of the grill, and the "legs" are located at the bottom. For the correct operation of the sensor, a 10 kΩ resistor must be soldered between the signal outputs and the power supply.

    If you have a ready-made sensor module in your hands, then connecting it to the Arduino is extremely simple: connect VCC to + 5V, GND to ground, the third pin to any free pin on the Arduino board. The pin number will then need to be specified in the sketch. In this way, you can connect the sensor to different Arduino boards: Uno, Arduino Mega, Arduino Nano, and others.
    The sensor module is connected according to the following scheme:

    SensorDHT22/DHT11 Arduino
    + +5V
    out e.g. 2
    GND

    Attention! Be sure to observe the polarity of the connection. In the event of an incorrect connection, the sensor will almost inevitably fail. In addition, if the plastic case of the sensor is not connected correctly, it will get very hot and can burn your hands. Be careful, don't rush!

    To match the circuit to the sketch example below, it is recommended to connect the signal from the DHT11/DHT22 humidity sensor to the second pin. If you have a different sketch, you can make the appropriate changes in the code and change the pin (example below). Additional resistors are also connected (this step can be omitted, since the board already has a resistor installed).

    Sketch for working with DHT11 and DHT22 sensors in Arduino

    Before writing the sketch, let's make sure we have the sensor library installed. humidity and temperature. You can download it from the link https://github.com/adafruit/DHT-sensor-library . A folder named "DHT-sensor-library-master" will load. It must be renamed to DHT and moved to the libraries folder, which is located in the root folder of the Arduino IDE. Next, you need to upload a ready-made sketch or write it yourself using examples. A typical arduino sketch for working with DHT11 and DHT22 looks like this:

    #include "DHT.h" #define DHTPIN 2 // Same pin number mentioned above // ​​One of the following lines is commented out. Remove comment if you connect DHT11 sensor to arduino DHT dht(DHTPIN, DHT22); //Sensor initiation //DHT dht(DHTPIN, DHT11); void setup() ( Serial.begin(9600); dht.begin(); ) void loop() ( delay(2000); // 2 second delay float h = dht.readHumidity(); //Measure humidity float t = dht.readTemperature(); //Measure temperature if (isnan(h) || isnan(t)) ( // Check. work Serial.println("Read error"); return; ) Serial.print("Humidity: "); Serial.print(h); Serial.print(" %\t"); Serial.print("Temperature: "); Serial.print(t); Serial.println(" *C "); //Printing indicators to the screen )

    After downloading the sketch and connecting the sensor, the measurement result can be viewed in the port monitor window. Temperature and humidity values ​​will be displayed there. If something went wrong, check the correct connection of the sensor, the correspondence of the port number on the Arduino board and in the sketch, the reliability of the contacts.
    If everything works and the sensor gives readings, you can conduct experiments. For example, put the sensor in a colder place or breathe on it, while tracking changes. If during fogging the level humidity increases, the sensor is working properly. Blow on it with a thin stream - the humidity will decrease and the temperature will return to normal.

    At this stage, you will be able to notice the difference between the actual temperature value and the arduino sensor readings. The accuracy of DHT11 is much worse than the accuracy of DHT22, which we have already discussed in this article. If you have both sensors, connect them to the Arduino board and compare the results. In my experience, the average discrepancy is more than a degree. Keep this in mind when using these sensors in your projects.

    Summary

    Let's summarize. The article discusses the issues of connecting arduino temperature and humidity sensors DHT11 and DHT22 to the board. Sensors are best purchased in the form of ready-made modules. To work with sensors, you can use the DHT library for Arduino, which is easy to download from the link indicated in the article. In the sketch, we simply initialize an object to work with the sensor and use its methods to get the temperature and humidity. We can view all the results obtained in the port monitor window, save and output to , send via or .

    Using DHT11 or DHT22 in arduino projects, you can build elements and smart greenhouses. Using these sensors, it is possible to create research complexes for climate measurements and environmental monitoring. The options for the areas of application of sensors are almost inexhaustible, you can find many examples on the Internet, including on this site. I hope that with the help of our article, you will not have any problems connecting DHT11 and DHT22 to Arduino.

When do you go somewhere far away for a certain period of time? There is no one to water your indoor flowers, so you have to ask for help from your neighbors, who, in turn, may be negligent about this. As a result, by your arrival, the plants will feel bad. To prevent this from happening, you can make an automatic irrigation system. For this purpose, we need an Arduino and a soil moisture sensor. In the article, we will consider an example of connecting and working with the FC-28 sensor. He has proven himself on the positive side, with the help of him thousands of projects have been created.

About the FC-28 sensor

There are a lot of sensors for determining soil moisture, but the most popular is the FC-28 model. It has a low price, due to which it is widely used by all radio amateurs in their projects. Soil moisture sensor with Arduino is used. He has two probes that conduct electrical current through the ground. It turns out that if the soil is wet, then the resistance between the probes is less. With dry ground, respectively, the resistance is greater. Arduino accepts these values, compares and, if necessary, turns on, for example, a pump. The sensor is able to work with both digital and analog modes, we will consider both connection options. FC-28 is used mainly in small projects, for example, when automatically watering one particular plant, since it is inconvenient to use it on a large scale due to its size and disadvantages, which we will also consider.

Where can I buy

The fact is that in Russian stores, sensors for working with Arduino are relatively expensive. The average price for this sensor in Russia varies from 200 to 300 rubles, while in Aliexpress the same sensor costs only some 30-50. The markup is huge. Of course, you can still make a sensor for measuring soil moisture with your own hands, but more on that below.

About connection

Connecting the humidity sensor to the Arduino is very easy. It comes with a comparator and a potentiometer for adjusting the sensitivity of the sensor, as well as for setting the limit value when connected using a digital output. The output signal, as mentioned above, can be digital and analog.

Connecting with a digital output

Connected in much the same way as analog:

  • VCC - 5V on Arduino.
  • D0 - D8 on the Arduino board.
  • GND is ground.

As mentioned above, a comparator and a potentiometer are located on the sensor module. Everything works as follows: using a potentiometer, we set the limit value of our sensor. FC-28 compares the value with the limit and then sends the value to the Arduino. Let's say the sensor values ​​are above the threshold, in which case the soil moisture sensor on the Arduino transmits 5V, if less - 0V. Everything is very simple, but the analog mode has more accurate values, so it is recommended to use it.

The electrical connection diagram looks like the one shown in the photo above. way

The code for the Arduino when using digital mode is shown below.

intled_pin=13; int sensor_pin=8; void setup() ( pinMode(led_pin, OUTPUT); pinMode(sensor_pin, INPUT); ) void loop() ( if(digitalRead(sensor_pin) == HIGH)( digitalWrite(led_pin, HIGH); ) else ( digitalWrite(led_pin, LOW); delay(1000); ) )

What does our code do? First, two variables were identified. The first variable - led_pin - serves to designate the LED, and the second - to designate the ground moisture sensor. Next, we declare the LED pin as an output, and the sensor pin as an input. This is necessary so that we can get the values, and if necessary, turn on the LED to visually see that the sensor values ​​are above the threshold. In the loop, we read the values ​​from the sensor. If the value is higher than the limit, turn on the LED, if it is lower, turn it off. Instead of an LED, there may be a pump, it all depends on you.

Analog mode

To connect using the analog output, you will need to work with A0. The capacitive soil moisture sensor in Arduino takes values ​​from 0 to 1023. We connect the sensor as follows:

  • VCC is connected to 5V to Arduino.
  • GND on the sensor is connected to GND on the Arduino board.
  • A0 is connected to A0 on the Arduino.

int sensor_pin = A0; int output_value ; void setup() ( Serial.begin(9600); Serial.println("Reading the sensor"); delay(2000); ) void loop() ( output_value= analogRead(sensor_pin); output_value = map(output_value,550,0,0,100); Serial.print("Moisture"); Serial.print(output_value); Serial.println("%"); delay(1000); )

So what does this code do? The first step was to set the variables. The first variable is needed to determine the contact of the sensor, and the other will store the results that we will receive using the sensor. Next, we read the data. In the loop, we write the values ​​from the sensor to the output_value variable we created. Then the percentage of soil moisture is calculated, after which we display them on the port monitor. The wiring diagram is shown below.

DIY

Above it was discussed how to connect the soil moisture sensor to the Arduino. The problem with these sensors is that they are short-lived. The fact is that they are very prone to corrosion. Some companies make sensors with a special coating to increase the service life, but it's still not the same. Also considered is the option of using the sensor not often, but only when required. For example, there is a program code where every second the sensor reads the soil moisture values. You can extend the service life if you turn it on, for example, once a day. But if this does not suit you, then you can make a soil moisture sensor with your own hands. Arduino will not feel the difference. Basically, the system is the same. Simply, instead of two sensors, you can put your own and use a material that is less susceptible to corrosion. Ideally, of course, use gold, but given its price, it will come out very expensive. In general, it's cheaper to buy, given the price of the FC-28.

Advantages and disadvantages

The article discussed options for connecting a soil moisture sensor to Arduino, and examples of program code were also presented. The FC-28 is a really good soil moisture sensor, but what are the specific pros and cons of this sensor?

Pros:

  • Price. This sensor has a very low price, so every radio amateur will be able to buy and build his own automatic watering system for plants. Of course, when working with large scales, this sensor will not work, but it is not intended for this. If you need a more powerful sensor - SM2802B, then you will have to pay a rather large amount for it.
  • Simplicity. Everyone can master working with this soil moisture sensor in Arduino. Just a few wires, a couple of lines of code - and that's it. Soil moisture control done.

Minuses:

  • Susceptibility to corrosion. This is the only drawback of these sensors. But given the price, you can close your eyes to this. First of all, these sensors were made more for training than for practical use in large projects.

The most frequently measured parameters in industry and everyday life are temperature and humidity. These values ​​are very important in drying wood, baking confectionery, in cold stores. In everyday life, they are measured in greenhouses and in heating and hot water circuits. The Arduino DHT11 sensor does its job perfectly and determines temperature and humidity more or less accurately.

From this article you will learn:

Greetings! Behind the keyboard Gridin Semyon and in this post I will show you how to connect the DHT11 temperature and humidity sensor, I will demonstrate the code and the library.

DHT11 sensor

DHT11 It's in a small plastic case. At the output of the sensor is a digital signal, and two parameters at once - temperature and humidity. The meaning of communication with the Arduino controller is as follows:

  1. The microcontroller requests readings and changes the signal from 0 to 1.
  2. The sensor sees the request and responds to it by changing the bit signal from 0 to 1.
  3. When they agreed among themselves, the sensor gives him a data packet of 5 bytes (40 bits), with the temperature in the first two bytes, humidity in the third and fourth. The fifth byte is a checksum to eliminate measurement errors.

Characteristics of the temperature and humidity sensor DHT11

  • Determination of humidity in the range of 20-80%
  • Temperature detection from 0°C to +50°C
  • Polling rate 1 time per second

The disadvantage of the sensor is that it does not have high accuracy and speed. The big plus is the price. Well, I think you already know this without me)).

The sensor contains a capacitive sensor for measuring humidity and a thermistor for measuring temperature. All readings are taken by the ADC chip and output a digital signal.

Industrial sensors usually provide an analog signal of 4-20 mA or 0-10 V. These are sensors that measure two parameters in pair. For example, the products of the company OWEN PVT10:

Write in the comments which ones do you use in your projects? Your opinion is very interesting...

On sale you can also find the second modification of the Arduino sensor - DHT22. I will say that the measurement range is much larger than the old version.

  • determination of humidity in the range of 0-100%
  • temperature detection from -40°C to +125°C
  • polling frequency 1 time per 2 seconds

Connecting the DHT11 sensor

Sensors are often made in the form of ready-made nameplates. At the output, it has 3 pins:

  • Power supply 5 V
  • Signal (S)
  • Ground GND

There is no need to set a resistance of 10 kOhm, since it is already soldered into the board. Connection diagram of the sensor and Arduino UNO.


Description of the program code

To work with our sensor, you need to connect a special library. It's called DHT.h . You can download here link.

And now let's take a look at the sketch of the program for working with the sensor.

Arduino

#include "DHT.h" #define DHTPIN 2 // number of the pin to which the sensor is connected // Uncomment according to the sensor used // Initiate the sensor //DHT dht(DHTPIN, DHT22); DHT dht(DHTPIN, DHT11); void setup() ( Serial.begin(9600); dht.begin(); ) void loop() ( // Delay 2 seconds between readings delay(1000); // Reading humidity float h = dht.readHumidity(); // Reading temperature float t = dht.readTemperature(); // Checking if reading was successful. if (isnan(h) || isnan(t)) ( Serial.println("Unable to read readings "); ) else ( Serial.print("Humidity: "); Serial.print(h); Serial.print("%\t"); Serial.print("Temperature: "); Serial.print(t); Serial.println(" *C"); ) )

#include "dht.h"

#define DHTPIN 2 // number of the pin to which the sensor is connected

// Uncomment according to the sensor being used

// Initiate the sensor

//DHT dht(DHTPIN, DHT22);

DHT dht (DHTPIN , DHT11 ) ;

void setup()(

Serial. begin(9600) ;

dht. start();

void loop()(

// Delay 2 seconds between measurements

delay(1000) ;

//Read humidity

float h = dht . readHumidity();

// Read temperature

float t = dht . readTemperature();

// Check if the read was successful.

if (isnan (h ) || isnan (t ) ) (

Serial. println( "Unable to take readings") ;

) else (

Serial. print("Humidity: ") ;

Serial. print(h);

Serial. print("%\t") ;

Port monitoring in Arduino IDE:

The program can include one interesting tool for viewing graphics. It can be turned on like this: Tools - Plotter via serial connection. I do not know, it only displays the temperature for me. If anyone knows how to use multiple charts, share in the comments. This is how the picture turned out:

If someone is not entirely clear, there is a great video tutorial from the guys.

This is where I end my post. In the next article I will write about. Write comments, ask questions, subscribe!

I wish you success!!!

Sincerely, Gridin Semyon.

Arduino Soil Moisture Sensor designed to determine the moisture content of the ground in which it is immersed. It lets you know if your house or garden plants are under or over watered. Connecting this module to the controller allows you to automate the process of watering your plants, garden or plantation (a kind of "smart watering").

The module consists of two parts: contact probe YL-69 and sensor YL-38, wires for connection are included. A small voltage is created between the two electrodes of the YL-69 probe. If the soil is dry, the resistance is high and the current will be less. If the ground is wet, the resistance is less, the current is slightly more. According to the final analog signal, one can judge the degree of humidity. The YL-69 probe is connected to the YL-38 probe via two wires. In addition to the pins for connecting to the probe, the YL-38 sensor has four pins for connecting to the controller.

  • Vcc – sensor power supply;
  • GND - ground;
  • A0 - analog value;
  • D0 is the digital value of the humidity level.
The YL-38 sensor is built on the basis of the LM393 comparator, which supplies voltage to the output D0 according to the principle: wet soil - low logic level, dry soil - high logic level. The level is determined by a threshold value that can be adjusted with a potentiometer. An analog value is applied to the A0 pin, which can be transferred to the controller for further processing, analysis and decision making. The YL-38 sensor has two LEDs that signal the presence of a power supply coming to the sensor and a digital signal level at the D0 output. The presence of a digital output D0 and a level LED D0 allows you to use the module autonomously, without connecting to the controller.

Module Specifications

  • Supply voltage: 3.3-5 V;
  • Current consumption 35 mA;
  • Output: digital and analog;
  • Module size: 16×30 mm;
  • Probe size: 20×60 mm;
  • Total weight: 7.5g

Usage example

Consider connecting a soil moisture sensor to an Arduino. Let's create a soil moisture indicator project for a houseplant (your favorite flower that you sometimes forget to water). To indicate the level of soil moisture, we will use 8 LEDs. For the project, we need the following details:
  • Arduino Uno Board
  • Soil moisture sensor
  • 8 LEDs
  • Bread board
  • Connecting wires.
We will assemble the circuit shown in the figure below


Let's start the Arduino IDE. Let's create a new sketch and add the following lines to it: // Soil moisture sensor // http: // site // contact for connecting the analog output of the sensor int aPin=A0; // pins for connecting indication LEDs int ledPins=(4,5,6,7,8,9,10,11); // variable for storing the sensor value int avalue=0; // variable number of glowing LEDs int countled=8; // full watering value int minvalue=220; // critical dryness value int maxvalue=600; void setup() ( // initialization of the serial port Serial.begin(9600); // setting the LED indication pins // to OUTPUT mode for(int i=0;i<8;i++) { pinMode(ledPins[i],OUTPUT); } } void loop() { // получение значения с аналогового вывода датчика avalue=analogRead(aPin); // вывод значения в монитор последовательного порта Arduino Serial.print("avalue=");Serial.println(avalue); // scale the value by 8 LEDs countled=map(avalue,maxvalue,minvalue,0,7); // indication of the humidity level for(int i=0;i<8;i++) ( if(i<=countled) digitalWrite(ledPins[i],HIGH); //light the LED else digitalWrite(ledPins[i],LOW); // turn off the LED ) // pause before the next value is received 1000 ms delay(1000); ) The analog output of the sensor is connected to the analog input of the Arduino, which is an analog-to-digital converter (ADC) with a resolution of 10 bits, which allows you to get values ​​​​from 0 to 1023 at the output. Greater dryness of the soil corresponds to a greater value of the analog signal. Using the map function, we scale the analog value of the sensor to the value of our LED indicator. The greater the soil moisture, the greater the value of the LED indicator (number of LEDs lit). By connecting this indicator to a flower, we can see the degree of humidity on the indicator from afar and determine the need for watering.

FAQ

1. Power LED is off
  • Check the presence and polarity of the power supplied to the YL-38 sensor (3.3 - 5 V).
2. When watering the soil, the soil moisture indicator LED does not light up
  • Set the threshold with the potentiometer. Check the connection of the YL-38 probe to the YL-69 probe.
3. When watering the soil, the value of the output analog signal does not change
  • Check the connection of the YL-38 probe to the YL-69 probe.
  • Check if the probe is in the ground.

We continue the series of lessons. Today we will analyze connection to Arduino temperature and humidity sensors DHT11 and DHT22.

The DHT11 and DHT22 sensors are not very fast or accurate, but they are simple, inexpensive, and great for training. They are made of two parts - a capacitive humidity sensor and a thermistor. The chip inside performs the A/D conversion and outputs a digital signal that can be read by any microcontroller.

Model Assembly Parts List

To build the project described in this tutorial, you will need the following parts:

  • Arduino board (more on how to choose an Arduino);
  • DHT11 or DHT22 sensor (you can buy, for example, or);
  • Breadboard;
  • 10 kΩ resistor;
  • The Arduino IDE program, which can be downloaded from the Arduino website.

DHT11 and DHT22 sensors

What is the difference between DHT11 and DHT22 sensors?

The two versions of the DHT sensors are similar and have the same pinout. Their differences are in characteristics. Specifications:

DHT11 sensor:

  • determination of humidity in the range of 20-80%
  • temperature detection from 0°C to +50°C
  • polling rate 1 time per second

DHT22 sensor:

  • determination of humidity in the range of 0-100%
  • temperature detection from -40°C to +125°C
  • polling frequency 1 time per 2 seconds

Thus, the performance of the DHT22 sensor is better compared to the DHT11, and therefore it is slightly more expensive. Taking readings more than once every 1-2 seconds will not work, but perhaps higher performance is not required for your project.

Connecting DHT Sensors to Arduino

DHT sensors have standard leads and are easy to mount on the breadboard.

DHT sensors have 4 pins:

  1. nutrition.
  2. data output
  3. not used.
  4. GND (ground).

Place a 10 kΩ resistor between the power and data output pins.

The DHT sensor is often sold as a complete module. In this case, it has three outputs and is connected without a resistor, because. The resistor is already on the board.

Connection diagram of a sensor with a resistor:

Wiring diagram for DHT sensor to Arduino

Arduino sketch

Let's use the DHT.h library, created specifically for DHT sensors. It can be downloaded. To use, you need to place the downloaded folder in the /libraries folder.

An example program for working a model with a DHT22 sensor (you can simply copy it to the Arduino IDE):
#include "dht.h"
#define DHTPIN 2 // number of the pin to which the sensor is connected
// Uncomment according to the sensor being used
// Initiate the sensor
DHT dht(DHTPIN, DHT22);
//DHT dht(DHTPIN, DHT11);
void setup()(
Serial.begin(9600);
dht.begin();
}
void loop() (
// Delay 2 seconds between measurements
delay(2000);
//Read humidity
float h = dht.readHumidity();
// Read temperature
float t = dht.readTemperature();
// Check if the read was successful.
if (isnan(h) || isnan(t)) (
Serial.println("Unable to read readings");
return;
}
Serial.print("Humidity: "+h+" %\t"+"Temperature: "+t+" *C ");
}
When using a DHT11 sensor, comment out the line:
DHT dht(DHTPIN, DHT22);
And uncomment the line:
//DHT dht(DHTPIN, DHT11);
Upload the sketch to the controller and check if it works correctly using Tools->Port Monitor:

Temperature and Humidity Readings (Port Monitor)

You should see temperature and humidity. Changes can be seen, for example, by exhaling at the sensor (as for fogging a window). Breathing increases moisture.

Lesson posts:

  1. First lesson:
  2. Second lesson:
  3. Third lesson:
  4. Fourth lesson:
  5. Fifth lesson:
  6. Sixth lesson:
  7. Seventh lesson:
  8. Eighth lesson:
  9. Ninth lesson: