Here’s the dht11 temperature and humidity sensor arduino code, you’ll need to use a library that simplifies communication with the sensor.
Below is a simple Arduino sketch to read data from a dht11 sensor and display the temperature and humidity on the Serial Monitor.
Components Needed for dht11 temperature and humidity sensor arduino code :
- Arduino (e.g., Uno)
- dht11 sensor
- Jumper wires
- Breadboard (optional)
- Resistor 4.7kΩ – 10kΩ (optional if using just the dht11 chip)
Aliexpress
Item | Image | Cost ($USD) |
dht11 sensor | $1.25 | |
arduino uno | $3.27 | |
jumper wires | $1.87 | |
breadboard | $1.53 | |
resistors | $1.11 (50 pieces) |
dht11 arduino Wiring and diagram:
- DHT11 Pin 1 (Data) to Digital Pin 2 on Arduino (or any other digital pin)
- DHT11 Pin 2 (VCC) to 5V on Arduino
- DHT11 Pin 3 (GND) to GND on Arduino
- Optional if using just using the dht11 chip; Using a breadboard, place a resistor between VCC and Data pin (4.7kΩ or 10kΩ)
dht11 temperature and humidity sensor arduino code
First, you’ll need to install the DHT
library. You can do this by going to Sketch > Include Library > Manage Libraries…, searching for “DHT sensor library” by Adafruit, and installing it.
// dht11 temperature and humidity sensor arduino code
#include "DHT.h"
#define DHTPIN 2 // Pin where the data pin of DHT11 is connected
#define DHTTYPE DHT11 // Define DHT type as DHT11
DHT dht(DHTPIN, DHTTYPE);
void setup() {
Serial.begin(9600);
dht.begin();
}
void loop() {
// Reading temperature or humidity takes about 250 milliseconds!
float humidity = dht.readHumidity();
float temperature = dht.readTemperature(); // For Fahrenheit use dht.readTemperature(true);
// Check if any reads failed and exit early (to try again).
if (isnan(humidity) || isnan(temperature)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
// Print temperature and humidity values to the Serial Monitor
Serial.print("Humidity: ");
Serial.print(humidity);
Serial.print(" %\t");
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.println(" *C");
delay(2000); // Wait a few seconds between measurements.
}
1. Reading Humidity and Temperature from dht11 temperature and humidity sensor arduino code
float humidity = dht.readHumidity();
float temperature = dht.readTemperature(); // For Fahrenheit use dht.readTemperature(true);
- Purpose: The first thing the loop does is read the humidity and temperature values from the DHT11 sensor.
dht.readHumidity()
: This function reads the humidity from the sensor and returns it as a floating-point number (e.g.,50.5
for 50.5% humidity).dht.readTemperature()
: This function reads the temperature from the sensor and returns it as a floating-point number in Celsius (e.g.,23.7
for 23.7°C). If you want the temperature in Fahrenheit, you would passtrue
to this function like this:dht.readTemperature(true)
.
2. Checking for Errors in the dht11 temperature and humidity sensor arduino code
if (isnan(humidity) || isnan(temperature)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
- Purpose: After attempting to read the sensor, the code checks if the readings were successful.
isnan()
Function: This function checks if the value returned from the sensor is “NaN” (Not a Number). If the sensor fails to provide a valid reading (due to a wiring issue or sensor malfunction), it might returnNaN
.- Condition Check: The code checks if either the
humidity
ortemperature
variable containsNaN
. - If there’s an error: If any of the readings failed, a message is printed to the Serial Monitor saying “Failed to read from DHT sensor!”, and the loop ends early using
return;
. This prevents the code from trying to print invalid data.
3. Displaying the dht11 Results
Serial.print("Humidity: ");
Serial.print(humidity);
Serial.print(" %\t");
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.println(" *C");
- Purpose: This section is responsible for displaying the temperature and humidity readings on the Serial Monitor.
Serial.print()
andSerial.println()
Functions:Serial.print("Humidity: ")
: Prints the string “Humidity: ” to the Serial Monitor.Serial.print(humidity)
: Prints the value of thehumidity
variable to the Serial Monitor.Serial.print(" %\t")
: Prints the percentage symbol%
followed by a tab (\t
) for spacing.Serial.print("Temperature: ")
: Prints the string “Temperature: ” to the Serial Monitor.Serial.print(temperature)
: Prints the value of thetemperature
variable to the Serial Monitor.Serial.println(" *C")
: Prints the string ” *C” (for Celsius) to the Serial Monitor and moves the cursor to a new line.
4. Delay Between Readings
delay(2000); // Wait a few seconds between measurements.
- Purpose: This line pauses the program for 2000 milliseconds (2 seconds) before the loop starts again.
- Why 2 Seconds?: The DHT11 sensor has a rate limit on how often it can provide readings, so adding a delay ensures that the sensor has enough time to stabilize before the next reading.
- and that the end of the dht11 temperature and humidity sensor arduino code!
dht sensor Summary:
- Read Data: The loop reads the humidity and temperature from the DHT11 sensor.
- Check for Errors: It checks if the readings are valid.
- Display Data: If the readings are valid, it prints the humidity and temperature values to the Serial Monitor.
- Wait: The program pauses for 2 seconds before taking the next reading.
- All elements combined this makes the dht11 temperature and humidity sensor arduino code work!
This loop repeats indefinitely, providing continuous temperature and humidity readings.
- The sketch initializes the DHT11 sensor and reads the temperature and humidity values every 2 seconds.
- The data is displayed in the Serial Monitor, showing the humidity in percentage and the temperature in Celsius.
- For more techincal spec and feature information on the dht11
Usage:
- Upload this sketch of the dht11 temperature and humidity sensor arduino code to your Arduino by ensuring the arduino is selected if it isn’t, use the drop down in the top left of the ide app, then select the option ‘Select other board and port’ scroll down to arduino uno and the port number your arduino is connected to.
Then press upload
- Open the Serial Monitor (
Ctrl + Shift + M
) to view the temperature and humidity readings.
Datasheet for dht11 temperature and humidity sensor arduino code
DHT11 Features & Specs | ||
---|---|---|
No. | Parameter | Value |
1 | Measures | Humidity & Temperature |
2 | Sensors Included | Capacitive Humidity Sensor & Thermistor |
3 | Humidity Range | 20% to 80% with ±5% accuracy |
4 | Temperature Range | 0°C to 50°C with ±2°C accuracy |
5 | Package | 4 Pins in a single row |
6 | Operating Voltage | 3.0V to 5.5V |
7 | Operating Current | 0.3mA(measuring), 60uA(idle) |
8 | Resolution | 1°C, 1%RH (8-Bit) |
9 | Response Time | 6s-15s |
10 | Repeatability | ±1°C, ±1%RH |
11 | Sampling Frequency | 1Hz |
12 | Dimensions | 27mm x 59mm x 13.5mm (1.05″ x 2.32″ x 0.53″) |
Официальная покупка диплома вуза с сокращенной программой обучения в Москве
Znáte nějaké metody, které by pomohly omezit krádeže obsahu? Rozhodně bych ocenil
) سأعيد زيارتها مرة أخرى لأنني قمت بوضع علامة كتاب عليها. المال والحرية هي أفضل طريقة للتغيير، أتمنى أن تكون غنيًا و
Znáte nějaké metody, které by pomohly omezit krádeže obsahu? Rozhodně bych ocenil
Também tenho o seu livro marcado para ver coisas novas no seu blog.
apreciariam o seu conteúdo. Por favor, me avise.
vykřiknout a říct, že mě opravdu baví číst vaše příspěvky na blogu.
مرحبًا، أعتقد أن هذه مدونة ممتازة. لقد عثرت عليها بالصدفة ;
díky tomuto nádhernému čtení! Rozhodně se mi líbil každý kousek z toho a já
vykřiknout a říct, že mě opravdu baví číst vaše příspěvky na blogu.
pokračujte v pěkné práci, kolegové.|Když máte tolik obsahu a článků, děláte to?
råb ud og sig, at jeg virkelig nyder at læse gennem dine blogindlæg.
مرحبًا، أعتقد أن هذه مدونة ممتازة. لقد عثرت عليها بالصدفة ;
information.|My family members every time say that I am killing my time here
har også bogmærket dig for at se på nye ting på din blog Hej! Har du noget imod, hvis jeg deler din blog med min facebook
With havin so much content and articles do you ever run into any problems of plagorism or copyright violation? My website has a lot of unique content I’ve either created myself or outsourced but it looks like a lot of it is popping it up all over the internet without my agreement. Do you know any methods to help reduce content from being stolen? I’d definitely appreciate it.
information.|My family members every time say that I am killing my time here
مرحبًا، أعتقد أن هذه مدونة ممتازة. لقد عثرت عليها بالصدفة ;
det. Denne side har bestemt alle de oplysninger, jeg ønskede om dette emne, og vidste ikke, hvem jeg skulle spørge. Dette er min 1. kommentar her, så jeg ville bare give en hurtig
at web, except I know I am getting familiarity all the time by reading thes pleasant posts.|Fantastic post. I will also be handling some of these problems.|Hello, I think this is a great blog. I happened onto it;) I have bookmarked it and will check it out again. The best way to change is via wealth and independence. May you prosper and never stop mentoring others.|I was overjoyed to find this website. I must express my gratitude for your time because this was an amazing read! I thoroughly enjoyed reading it, and I’ve bookmarked your blog so I can check out fresh content in the future.|Hi there! If I shared your blog with my Facebook group, would that be okay? I believe there are a lot of people who would truly value your article.|منشور رائع. سأتعامل مع بعض هذه|
på grund af denne vidunderlige læsning !!! Jeg kunne bestemt virkelig godt lide hver eneste lille smule af det, og jeg
) سأعيد زيارتها مرة أخرى لأنني قمت بوضع علامة كتاب عليها. المال والحرية هي أفضل طريقة للتغيير، أتمنى أن تكون غنيًا و
Díky moc!|Hej, jeg synes, dette er en fremragende blog. Jeg snublede over det;
Esta página tem definitivamente toda a informação que eu queria sobre este assunto e não sabia a quem perguntar. Este é o meu primeiro comentário aqui, então eu só queria dar um rápido
Kender du nogen metoder, der kan hjælpe med at forhindre, at indholdet bliver stjålet? Det ville jeg sætte stor pris på.
Díky moc!|Hej, jeg synes, dette er en fremragende blog. Jeg snublede over det;
|Hello to all, for the reason that I am actually keen of
ocenili váš obsah. Dejte mi prosím vědět.
værdsætter dit indhold. Lad mig venligst vide det.
Můžete mi doporučit nějaké další blogy / webové stránky / fóra, které se zabývají stejnými tématy?
že spousta z něj se objevuje na internetu bez mého souhlasu.
Znáte nějaké metody, které by pomohly omezit krádeže obsahu? Rozhodně bych ocenil
buď vytvořil sám, nebo zadal externí firmě, ale vypadá to.
Nice i really enjoyed reading your blogs. Keep on posting. Thanks
Díky moc!|Hej, jeg synes, dette er en fremragende blog. Jeg snublede over det;
que eu mesmo criei ou terceirizei, mas parece que
Fiquei muito feliz em descobrir este site. Preciso de agradecer pelo vosso tempo
på grund af denne vidunderlige læsning !!! Jeg kunne bestemt virkelig godt lide hver eneste lille smule af det, og jeg
Esta página tem definitivamente toda a informação que eu queria sobre este assunto e não sabia a quem perguntar. Este é o meu primeiro comentário aqui, então eu só queria dar um rápido
webside er virkelig bemærkelsesværdig for folks oplevelse, godt,
) Vou voltar a visitá-lo uma vez que o marquei no livro. O dinheiro e a liberdade são a melhor forma de mudar, que sejas rico e continues a orientar os outros.
Thanks so much for the blog.Thanks Again. Really Great.
que eu mesmo criei ou terceirizei, mas parece que
apreciariam o seu conteúdo. Por favor, me avise.
I was suggested this blog by my cousin. I am not sure whether this post is written by him as no one else know such detailed about my difficulty. You’re incredible! Thanks!
I love your wp web template, wherever do you get a hold of it through?
I think this is among the most vital information for me. And i’m glad reading your article. But wanna remark on few general things, The site style is perfect, the articles is really excellent : D. Good job, cheers
I truly appreciate this article.Much thanks again. Cool.
مرحبًا، أعتقد أن هذه مدونة ممتازة. لقد عثرت عليها بالصدفة ;
Im thankful for the post.Really looking forward to read more. Great.
Say, you got a nice blog article.Thanks Again. Awesome.
I am so grateful for your post.Thanks Again. Really Cool.
Thanks so much for the post.Really thank you!
I value the blog post.Really thank you!
الاستمرار في توجيه الآخرين.|Ahoj, věřím, že je to vynikající blog. Narazil jsem na něj;
This is one awesome article.Thanks Again. Will read on…