Offline
Зарегистрирован: 30.07.2017
Подключил dht11 к arduino uno от robotdynю Не работает. Не удаётся считать данные с датчика. Я попробовал множество библиотек. И разных кодов. Прикрепил последний, который использую. Помогите завести датчик.
Использую этот код
/*
* TempHumidity.cpp
*
* Sample driver application to test the Dht11 module.
*/
#include «Arduino.h»
#include «Dht11.h»
enum {
// The data I/O pin connected to the DHT11 sensor
DHT_DATA_PIN = 2,
// The baud rate of the serial interface
SERIAL_BAUD = 9600,
// The delay between sensor polls.
POLL_DELAY = 2000,
};
/*
* setup
*
* One-time initialization of the module.
*/
void setup() {
Serial.begin(SERIAL_BAUD);
Serial.print(«Dht11 Lib version «);
Serial.println(Dht11::VERSION);
}
/*
* loop
*
* Code to be executed repeatedly.
*/
void loop() {
static Dht11 sensor(DHT_DATA_PIN);
switch (sensor.read()) {
case Dht11::OK:
Serial.print(«Humidity (%): «);
Serial.println(sensor.getHumidity());
Serial.print(«Temperature (C): «);
Serial.println(sensor.getTemperature());
break;
case Dht11::ERROR_CHECKSUM:
Serial.println(«Checksum error»);
break;
case Dht11::ERROR_TIMEOUT:
Serial.println(«Timeout error»);
break;
default:
Serial.println(«Unknown error»);
break;
}
delay(POLL_DELAY);
}
I get this error every time. I used the DHT tester file from this library. Which gives me an error.
And then I realized that in my code Arduino recognizes only the readTemperature
function, not readHumidity
, but it doesn’t give any compile error. Also, when I read the sensor, this is the output:
Humidity Sensor Test
Temp: 0C, Humidity: 0%
Temp: 0C, Humidity: 0%
Temp: 0C, Humidity: 0%
My code is here:
//DHT11 Sensor:
#include "DHT.h"
#define DHTPIN 5 // which digital pin we're connected to
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);
//I2C LCD:
#include <Wire.h> // Comes with Arduino IDE
#include <LiquidCrystal_I2C.h>
// Set the LCD I2C address
LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);
void setup() {
Serial.begin(9600);
delay(300);
lcd.begin(16,2);
Serial.println("Humidity Sensor Test");
dht.begin();
delay(300);
}
void loop() {
// Reading temperature or humidity takes about 250 milliseconds!
// Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
int h = dht.readHumidity();
int t = dht.readTemperature();
// set the cursor to (0,0):
lcd.setCursor(0, 0);
// print from 0 to 9:
lcd.print("Temp: ");
lcd.print(t);
lcd.print("C");
// set the cursor to (16,1):
lcd.setCursor(0,1);
lcd.print("Humidity: ");
lcd.print(h);
lcd.print("%");
Serial.print("Temp: ");
Serial.print(t);
Serial.print("C, Humidity: ");
Serial.print(h);
Serial.println("%");
delay(2500);
}
Also I have the 10k resistor between data and Vcc pins. Data is connected to digital pin 5. Has anyone had this problem before?
I get this error every time. I used the DHT tester file from this library. Which gives me an error.
And then I realized that in my code Arduino recognizes only the readTemperature
function, not readHumidity
, but it doesn’t give any compile error. Also, when I read the sensor, this is the output:
Humidity Sensor Test
Temp: 0C, Humidity: 0%
Temp: 0C, Humidity: 0%
Temp: 0C, Humidity: 0%
My code is here:
//DHT11 Sensor:
#include "DHT.h"
#define DHTPIN 5 // which digital pin we're connected to
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);
//I2C LCD:
#include <Wire.h> // Comes with Arduino IDE
#include <LiquidCrystal_I2C.h>
// Set the LCD I2C address
LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);
void setup() {
Serial.begin(9600);
delay(300);
lcd.begin(16,2);
Serial.println("Humidity Sensor Test");
dht.begin();
delay(300);
}
void loop() {
// Reading temperature or humidity takes about 250 milliseconds!
// Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
int h = dht.readHumidity();
int t = dht.readTemperature();
// set the cursor to (0,0):
lcd.setCursor(0, 0);
// print from 0 to 9:
lcd.print("Temp: ");
lcd.print(t);
lcd.print("C");
// set the cursor to (16,1):
lcd.setCursor(0,1);
lcd.print("Humidity: ");
lcd.print(h);
lcd.print("%");
Serial.print("Temp: ");
Serial.print(t);
Serial.print("C, Humidity: ");
Serial.print(h);
Serial.println("%");
delay(2500);
}
Also I have the 10k resistor between data and Vcc pins. Data is connected to digital pin 5. Has anyone had this problem before?
-
#1
Имеется: NODEMCU V3, датчик температуры и влажности DHT11
Прошивка:
Код:
NodeMCU custom build by frightanic.com
branch: master
commit: 11592951b90707cdcb6d751876170bf4da82850d
SSL: false
modules: dht,file,gpio,http,i2c,mqtt,net,node,sjson,tmr,uart,websocket,wifi
build created on 2018-12-30 19:20
powered by Lua 5.1.4 on SDK 2.2.1(6ab97e9)
Скетч самый простой отсюда:
Код:
pin = 5
status, temp, humi, temp_dec, humi_dec = dht.read(pin)
if status == dht.OK then
-- Integer firmware using this example
print(string.format("DHT Temperature:%d.%03d;Humidity:%d.%03drn",
math.floor(temp),
temp_dec,
math.floor(humi),
humi_dec
))
-- Float firmware using this example
print("DHT Temperature:"..temp..";".."Humidity:"..humi)
elseif status == dht.ERROR_CHECKSUM then
print( "DHT Checksum error." )
elseif status == dht.ERROR_TIMEOUT then
print( "DHT timed out." )
end
Вот такие значения приходят с датчика:
DHT Temperature:665.900;Humidity:947.200
Значения увеличиваются/уменьшаются в соответствии с изменениями окруж. среды. Вот только приходят в неверном формате. Может кто сталкивался?
Последнее редактирование: 3 Янв 2019
-
#2
Перепрошил на AT v0.23 SDK 1.0.1. С бибилиотекой DHT-sensor-library для Arduino IDE все работает нормально. Показатели с датчика приходят корректные. А вот с LUA прошивкой успехов так и не добился…
Последнее редактирование: 3 Янв 2019
-
#3
Попробуйте время опроса датчика сделать не чаще чем две секунды.
-
#4
Попробуйте время опроса датчика сделать не чаще чем две секунды.
Сначала тоже так подумал. Так вот мой скрипт не выполняется циклично, а только один раз, если отправить команду dofile(«script1.lua»). Соответственно датчик опрашивается единожды. Наверно дело не в частоте опроса датчика..
-
#5
Сначала тоже так подумал. Так вот мой скрипт не выполняется циклично, а только один раз, если отправить команду dofile(«script1.lua»). Соответственно датчик опрашивается единожды. Наверно дело не в частоте опроса датчика..
Считайте два раза. Посмотрите результат второго считывания. Конечно с промежутком в 2 секунды.
-
#6
Считайте два раза. Посмотрите результат второго считывания. Конечно с промежутком в 2 секунды.
Изменил скрипт, как вы сказали: опрашиваю теперь дважды с паузой в 2 сек. Паузу вызываю следующим методом:
Код:
socket = require("socket")
function sleep(sec)
socket.sleep(sec)
end
sleep(2)
Ответ приходит все такой же:
DHT Temperature:665.900;Humidity:947.200
DHT Temperature:671.000;Humidity:1150.300
Подышал на датчик в промежутке между двумя запросами показаний — видно, что показания меняются
Пробовал использовать функцию dht.read11() вместо dht.read() для считывания показаний — приходит ошибка dht.ERROR_CHECKSUM
Последнее редактирование: 3 Янв 2019
-
#7
Интересует такая же проблема.
Прошивку NodeMCU Lua SDK 2.2.1 брал отсюда NodeMCU custom builds
Я еще кроме этого подцепил резистор 10 кОм на +3,3В на Дата выход датчика DHT11.
Всё равно не помогло, датчик возвращает левые цифры.
Иногда (может раз в 10 минут) появляются корректная Температура и Влажность.
Последнее редактирование: 27 Янв 2019
-
#8
у меня тоже с dht11какието левые значения.. лежит на окне, показывает 8-10-15 влажность.. если подышать влажность растет..
-
35.1 KB
Просмотры: 3
-
#9
у меня тоже с dht11какието левые значения.. лежит на окне, показывает 8-10-15 влажность.. если подышать влажность растет..
смотрите программу
вот здесь есть пример как выводить данные датчика в луа.
dht — NodeMCU Documentation
-
#10
Пробовал использовать функцию dht.read11() вместо dht.read() для считывания показаний — приходит ошибка dht.ERROR_CHECKSUM
А у меня только этот вариант прокатил. Просто добавит «11», и всё.
I get this error every time. I used the DHT tester file from this library. Which gives me an error.
And then I realized that in my code Arduino recognizes only the readTemperature
function, not readHumidity
, but it doesn’t give any compile error. Also, when I read the sensor, this is the output:
Humidity Sensor Test
Temp: 0C, Humidity: 0%
Temp: 0C, Humidity: 0%
Temp: 0C, Humidity: 0%
My code is here:
//DHT11 Sensor:
#include "DHT.h"
#define DHTPIN 5 // which digital pin we're connected to
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);
//I2C LCD:
#include <Wire.h> // Comes with Arduino IDE
#include <LiquidCrystal_I2C.h>
// Set the LCD I2C address
LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);
void setup() {
Serial.begin(9600);
delay(300);
lcd.begin(16,2);
Serial.println("Humidity Sensor Test");
dht.begin();
delay(300);
}
void loop() {
// Reading temperature or humidity takes about 250 milliseconds!
// Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
int h = dht.readHumidity();
int t = dht.readTemperature();
// set the cursor to (0,0):
lcd.setCursor(0, 0);
// print from 0 to 9:
lcd.print("Temp: ");
lcd.print(t);
lcd.print("C");
// set the cursor to (16,1):
lcd.setCursor(0,1);
lcd.print("Humidity: ");
lcd.print(h);
lcd.print("%");
Serial.print("Temp: ");
Serial.print(t);
Serial.print("C, Humidity: ");
Serial.print(h);
Serial.println("%");
delay(2500);
}
Also I have the 10k resistor between data and Vcc pins. Data is connected to digital pin 5. Has anyone had this problem before?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 |
#include <ESP8266WiFi.h> #include "DHT.h" // оставляем раскомментированной строчку, // соответствующую модели вашего датчика: #define DHTTYPE DHT11 // DHT 11 //#define DHTTYPE DHT21 // DHT 21 (AM2301) //#define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321 // вписываем здесь данные для своей WiFi-сети: const char* ssid = "11122"; const char* password = "83491583"; // веб-сервер на порте 80: WiFiServer server(80); // датчик DHT: const int DHTPin = 3; // инициализируем датчик DHT: DHT dht(DHTPin, DHTTYPE); // временные переменные: static char celsiusTemp[7]; static char fahrenheitTemp[7]; static char humidityTemp[7]; // этот блок будет запускаться только при загрузке ESP: void setup() { // инициализируем последовательный порт (в отладочных целях): Serial.begin(115200); delay(10); dht.begin(); // подключаемся к WiFi-сети: Serial.println(); Serial.print("Connecting to "); // "Подключаемся к " Serial.println(ssid); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.println("WiFi connected"); // "Подключение к WiFi выполнено" // запускаем веб-сервер: server.begin(); Serial.println("Web server running. Waiting for the ESP IP..."); // "Веб-сервер запущен. Ждем IP-адрес ESP..." delay(10000); // печатаем IP-адрес ESP: Serial.println(WiFi.localIP()); } // этот блок будет запускаться снова и снова: void loop() { // начинаем прослушку новых клиентов: WiFiClient client = server.available(); if (client) { Serial.println("New client"); // "Новый клиент" // создаем переменную типа «boolean», // чтобы определить конец HTTP-запроса: boolean blank_line = true; while (client.connected()) { if (client.available()) { char c = client.read(); if (c == 'n' && blank_line) { // данные от датчика могут запаздывать на 2 секунды // (это очень медленный датчик): float h = dht.readHumidity(); // считываем температуру в Цельсиях (по умолчанию): float t = dht.readTemperature(); // считываем температуру в Фаренгейтах // (isFahrenheit = true): float f = dht.readTemperature(true); // проверяем, прочитались ли данные от датчика, // и если нет, то выходим и начинаем заново: if (isnan(h) || isnan(t) || isnan(f)) { Serial.println("Failed to read from DHT sensor!"); // "Не удалось прочитать // данные от датчика DHT" strcpy(celsiusTemp,"Failed"); strcpy(fahrenheitTemp, "Failed"); strcpy(humidityTemp, "Failed"); } else{ // рассчитываем градусы в Цельсиях и Фаренгейтах, // а также влажность: float hic = dht.computeHeatIndex(t, h, false); dtostrf(hic, 6, 2, celsiusTemp); float hif = dht.computeHeatIndex(f, h); dtostrf(hif, 6, 2, fahrenheitTemp); dtostrf(h, 6, 2, humidityTemp); // все эти Serial.print() ниже можно удалить, // т.к. они для отладочных целей: Serial.print("Humidity: "); // "Влажность: " Serial.print(h); Serial.print(" %t Temperature: "); // "Температура: " Serial.print(t); Serial.print(" *C "); Serial.print(f); Serial.print(" *Ft Heat index: "); // "Тепловой индекс: " Serial.print(hic); Serial.print(" *C "); Serial.print(hif); Serial.print(" *F"); Serial.print("Humidity: "); // "Влажность: " Serial.print(h); Serial.print(" %t Temperature: "); // "Температура: " Serial.print(t); Serial.print(" *C "); Serial.print(f); Serial.print(" *Ft Heat index: "); // "Тепловой индекс: " Serial.print(hic); Serial.print(" *C "); Serial.print(hif); Serial.println(" *F"); } client.println("HTTP/1.1 200 OK"); client.println("Content-Type: text/html"); client.println("Connection: close"); client.println(); // веб-страница, отображающая температуру и влажность: client.println("<!DOCTYPE HTML>"); client.println("<html>"); client.println("<head></head><body><h1>ESP8266 - Temperature and Humidity</h1><h3>Temperature in Celsius: "); client.println(celsiusTemp); client.println("*C</h3><h3>Temperature in Fahrenheit: "); client.println(fahrenheitTemp); client.println("*F</h3><h3>Humidity: "); client.println(humidityTemp); client.println("%</h3><h3>"); client.println("</body></html>"); break; } if (c == 'n') { // если обнаружен переход на новую строку: blank_line = true; } else if (c != 'r') { // если в текущей строчке найден символ: blank_line = false; } } } // закрываем соединение с клиентом: delay(1); client.stop(); Serial.println("Client disconnected."); // "Клиент отключен." } } |
This is a troubleshooting guide for the most common issues with the DHT sensor when using ESP32, ESP8266, Arduino, or similar boards.
If you get an error message in your serial Monitor while reading the temperature and humidity from the DHT11, DHT22, AM2302 or AM2301 sensor, follow the next steps to see if you can make it work.
“Failed to read from DHT sensor!” or Nan readings
If your DHT11/DHT22 sensor returns the error message “Failed to read from DHT sensor!” or the DHT readings return “Nan”:
Try one of the next troubleshooting tips.
1. Wiring
When you’re building an electronics project, you need to double-check the wiring or pin assignment. After checking and testing that your circuit is properly connected, if it still doesn’t work, continue reading the next troubleshooting tips.
2. Power
The DHT sensor has an operating range of 3V to 5.5V (DHT11) or 3V to 6V (DHT22). If you’re powering the sensor from a 3.3V pin, in some cases powering the DHT with 5V solves the problem.
3. Bad USB port or USB cable
Sometimes powering the ESP32, ESP8266, Arduino or similar boards directly from a PC USB port is not enough. Try to plug it to a USB hub powered by an external power source. It might also help replacing the USB cable with a better or shorter one. Having a USB port that supplies enough power or using a good USB cable often fixes this problem.
4. Power source
As mentioned in the previous tip, your board (ESP32, ESP8266, Arduino, etc) might not be supplying enough power to properly read from the DHT sensor. In some cases, you might need to power your board with a power source that provides more current.
5. Sensor type
Double-check that you’ve uncommented/commented in your code the right sensor for your project. In this case, we are selecting the DHT22:
//#define DHTTYPE DHT11 // DHT 11
#define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321
//#define DHTTYPE DHT21 // DHT 21 (AM2301)
6. Sampling rate
The DHT sensor is very slow getting the readings (the sensor readings may take up to 2 seconds). In some cases, increasing the time between readings solves the problem.
7. DHT sensor is fried or broken
Unfortunately, these cheap sensors sometimes look totally fine, but they are fried/broken. So, even though you assembled the right circuit and code, it will still fail to get the readings. Try to use a different sensor to see if it fixes your problem.
8. Wrong baud rate or failed to upload code
If you don’t see anything in your Arduino IDE Serial Monitor, double-check that you’ve selected the right baud rate, COM port or that you’ve uploaded the code successfully.
While building our projects, we’ve experienced similar issues with the DHT and it was always solved by following one of the methods described earlier.
Fatal error: Adafruit_Sensor.h: No such file or directory
There’s also a common error that happens when you try to compile the code. If you receive the following error:
fatal error: Adafruit_Sensor.h: No such file or directory
#include <Adafruit_Sensor.h>
You need to install the Adafruit Unified Sensor driver library. In your Arduino IDE, type in the search box “Adafruit Unified Sensor“, scroll all the way down to find the library and install it.
After installing the library, restart your Arduino IDE and the code should compile without the error message.
Wrapping Up
We hope you’ve found this guide useful. If you encounter any other issues, please post them in comments below and we’ll try to help you solve your problem.
We have other tutorials with DHT sensors that you might find useful:
- Complete Guide for DHT11/DHT22 with ESP32
- Complete Guide for DHT11/DHT22 with Arduino board
- Complete Guide for DHT11/DHT22 using MicroPython with ESP32/ESP8266
- ESP32 DHT11/DHT22 Web Server using Arduino IDE
- ESP8266 DHT11/DHT22 Web Server using Arduino IDE
- MicroPython: ESP32/ESP8266 with DHT11/DHT22 Web Server
Thanks for reading.