Error dht11 was not declared in this scope

I'm getting this and I don't know how to resolve this. If someone could help me I'd appreciate it. DHTtester.ino:4:17: error: DHT.h: No such file or directory DHTtester:18: error: '...

This is the actual code
Pls help in finding errors

#include <Adafruit_GFX.h>
#include <Adafruit_PCD8544.h>
#include <Wire.h> // this #include still required because the RTClib depends on it
#include «RTClib.h»
#include «DHT.h»
#define DHT11_PIN A0 // what pin we’re connected to
#define DHTTYPE DHT11 // DHT 11
DHT dht(DHT11_PIN, DHTTYPE);
RTC_Millis rtc;
int contrast=50;
int Temp;
int Humi;
int umi=0;
int digits;
int digitt;
boolean light = true;
volatile boolean buttonA = false;
volatile boolean buttonB = false;
volatile boolean buttonC = false;
int StateOfbuttonA = 0;
int StateOfbuttonB = 0;
int StateOfbuttonC = 0;
int NewStateOfbuttonA = 0;
int NewStateOfbuttonB = 0;
int NewStateOfbuttonC = 0;
int yearr = 2017;
int dayy = 1;
int monthh = 1;
int hourr = 0;
int minutee = 0;
int secondd = 0;
Adafruit_PCD8544 display = Adafruit_PCD8544(7, 6, 5, 4, 3);

void setup() {
pinMode(11, INPUT_PULLUP);
pinMode(10, INPUT_PULLUP);
pinMode(9, INPUT_PULLUP);
pinMode(8,OUTPUT);
digitalWrite(8,LOW); //Turn Backlight ON
dht.begin();
display.begin();
display.setContrast(contrast); //Set contrast to 50
display.clearDisplay();
display.display();
rtc.begin(DateTime(F(DATE), F(TIME)));
}

void loop() {
NewStateOfbuttonA = digitalRead(9);
NewStateOfbuttonB = digitalRead(10);
NewStateOfbuttonC = digitalRead(11);
buttonAisPressed();
buttonBisPressed();
buttonCisPressed();
if (buttonA) {
if (umi == 1 ) {
buttonA = false;
contrast++;
setContrast();
}
else if (umi == 2 ) {
buttonA = false;
yearr++;
rtc.adjust(DateTime(yearr,monthh,dayy,hourr,minutee,secondd));
}
else if (umi == 3 ) {
buttonA = false;
monthh++;
rtc.adjust(DateTime(yearr,monthh,dayy,hourr,minutee,secondd));
}
else if (umi == 4 ) {
buttonA = false;
dayy++;
rtc.adjust(DateTime(yearr,monthh,dayy,hourr,minutee,secondd));
}
else if (umi == 5 ) {
buttonA = false;
hourr++;
rtc.adjust(DateTime(yearr,monthh,dayy,hourr,minutee,secondd));
}
else if (umi == 6 ) {
buttonA = false;
minutee++;
rtc.adjust(DateTime(yearr,monthh,dayy,hourr,minutee,secondd));
}
else if (umi == 7 ) {
buttonA = false;
rtc.adjust(DateTime(yearr,monthh,dayy,hourr,minutee,0));
}
else if (umi == 8 ) {
buttonA = false;
if (light)
{
light = false;
lightOff();
}
else
{
light = true;
lightOn();
}
}
}
if (buttonB) {
buttonB = false;
umi++;
if (umi == 9 ) {
umi = 0;
}
}
if (buttonC) {
if (umi == 1 ) {
buttonC = false;
contrast—;
setContrast();
}
else if (umi == 2 ) {
buttonC = false;
yearr—;
rtc.adjust(DateTime(yearr,monthh,dayy,hourr,minutee,secondd));
}
else if (umi == 3 ) {
buttonC = false;
monthh—;
rtc.adjust(DateTime(yearr,monthh,dayy,hourr,minutee,secondd));
}
else if (umi == 4 ) {
buttonC = false;
dayy—;
rtc.adjust(DateTime(yearr,monthh,dayy,hourr,minutee,secondd));
}
else if (umi == 5 ) {
buttonC = false;
hourr—;
rtc.adjust(DateTime(yearr,monthh,dayy,hourr,minutee,secondd));
}
else if (umi == 6 ) {
buttonC = false;
minutee—;
rtc.adjust(DateTime(yearr,monthh,dayy,hourr,minutee,secondd));
}
else if (umi == 7 ) {
buttonC = false;
rtc.adjust(DateTime(yearr,monthh,dayy,hourr,minutee,0));
}
else if (umi == 8 ) {
buttonC = false;
if (light)
{
light = false;
lightOff();
}
else
{
light = true;
lightOn();
}
}

}
digitalDisplay();
}

void digitalDisplay(){
Temp = dht.readTemperature();
Humi = dht.readHumidity();
DateTime now = rtc.now();

printDigitt(now.year());
yearr == digitt;
printDigitt(now.month());
dayy == digitt;
printDigitt(now.day());
monthh == digitt;
printDigitt(now.hour());
hourr == digitt;
printDigitt(now.minute());
minutee == digitt;
printDigitt(now.second());
secondd == digitt;

// digital clock display of the time
display.setTextSize(1);
display.clearDisplay();
if (umi == 1)
{
display.setCursor(5, 0);
display.print(contrast);
}
if (umi == 8)
{
display.setCursor(7, 0);
display.print(«*»);
}
display.setTextColor(BLACK, WHITE);
display.setCursor(24, 0);
if (umi == 2)
{
display.setTextColor(WHITE, BLACK);
}
else
{
display.setTextColor(BLACK, WHITE);
}
printDigits(now.year());
display.setTextColor(BLACK, WHITE);
display.print(‘/’);
if (umi == 3)
{
display.setTextColor(WHITE, BLACK);
}
else
{
display.setTextColor(BLACK, WHITE);
}
printDigits(now.month());
display.setTextColor(BLACK, WHITE);
display.print(‘/’);
if (umi == 4)
{
display.setTextColor(WHITE, BLACK);
}
else
{
display.setTextColor(BLACK, WHITE);
}
printDigits(now.day());
if (umi == 7)
{
display.setTextColor(WHITE, BLACK);
}
else
{
display.setTextColor(BLACK, WHITE);
}
display.setCursor(72, 20);
printDigits(now.second());
display.setTextSize(2);
display.setCursor(10, 14);
if (umi == 5)
{
display.setTextColor(WHITE, BLACK);
}
else
{
display.setTextColor(BLACK, WHITE);
}
printDigits(now.hour());
display.setTextColor(BLACK, WHITE);
display.print(‘:’);
if (umi == 6)
{
display.setTextColor(WHITE, BLACK);
}
else
{
display.setTextColor(BLACK, WHITE);
}
printDigits(now.minute());
display.setTextColor(BLACK, WHITE);
display.setCursor(0, 32);
display.setTextSize(1);
display.print(«T»);
display.setCursor(6, 32);
display.setTextSize(2);
display.print(Temp);
display.print(«c»);
display.setCursor(42, 32);
display.setTextSize(1);
display.print(«H»);
display.setCursor(48, 32);
display.setTextSize(2);
display.print(Humi);
display.print(«%»);
display.display();
}
void printDigits(int digits){
// utility function for digital clock display: prints preceding colon and leading 0
if(digits < 10){
display.print(‘0’);
display.print(digits);
}
else
{
display.print(digits);
}
}

void buttonAisPressed()
{
if (NewStateOfbuttonA != StateOfbuttonA)
{
if (NewStateOfbuttonA == 0)
{
buttonA=true;
}
delay(50);
}
StateOfbuttonA = NewStateOfbuttonA;
}

void buttonBisPressed()
{
if (NewStateOfbuttonB != StateOfbuttonB)
{
if (NewStateOfbuttonB == 0) {
buttonB=true;
}
delay(50);
}
StateOfbuttonB = NewStateOfbuttonB;
}

void buttonCisPressed()
{
if (NewStateOfbuttonC != StateOfbuttonC)
{
if (NewStateOfbuttonC == 0) {
buttonC=true;
}
delay(50);
}
StateOfbuttonC = NewStateOfbuttonC;
}
void lightOn()
{
digitalWrite(8,LOW);
}

{
digitalWrite(8,HIGH);
}

void setContrast()
{
display.setContrast(contrast);
display.display();
}
void printDigitt(int digitt){
digitt == digitt;
}

Страница 3 из 3

  1. Геморой какой то с этой библиотекой. Может кто знает где она в папке выложена?

  2. Ругань компилятора в студию.

  3. Не выходит каменный цветок. С этой тоже ошибки пишет.

  4. Arduino: 1.5.6-r2 (Windows 7), Board: «Arduino Uno»

    dva_dht22:4: error: ‘dht’ does not name a type
    dva_dht22.ino: In function ‘void setup()’:
    dva_dht22:14: error: ‘DHT_LIB_VERSION’ was not declared in this scope
    dva_dht22.ino: In function ‘void loop()’:
    dva_dht22:24: error: expected primary-expression before ‘.’ token
    dva_dht22:27: error: ‘DHTLIB_OK’ was not declared in this scope
    dva_dht22:30: error: ‘DHTLIB_ERROR_CHECKSUM’ was not declared in this scope
    dva_dht22:33: error: ‘DHTLIB_ERROR_TIMEOUT’ was not declared in this scope
    dva_dht22:45: error: expected primary-expression before ‘.’ token
    dva_dht22:47: error: expected primary-expression before ‘.’ token
    dva_dht22:56: error: expected primary-expression before ‘.’ token
    dva_dht22:59: error: ‘DHTLIB_OK’ was not declared in this scope
    dva_dht22:62: error: ‘DHTLIB_ERROR_CHECKSUM’ was not declared in this scope
    dva_dht22:65: error: ‘DHTLIB_ERROR_TIMEOUT’ was not declared in this scope
    dva_dht22:75: error: expected primary-expression before ‘.’ token
    dva_dht22:77: error: expected primary-expression before ‘.’ token

    This report would have more information with
    «Show verbose output during compilation»
    enabled in File > Preferences.

  5. вот код.

    #include <dht.h>

    dht DHT;

    #define DHT22a_PIN 5
    #define DHT22b_PIN 6

    void setup()
    {
    Serial.begin(115200);
    Serial.println(«DHT TEST PROGRAM «);
    Serial.print(«LIBRARY VERSION: «);
    Serial.println(DHT_LIB_VERSION);
    Serial.println();
    Serial.print(«Type,tstatus,tHumidity (%),tTemperature (C)»);
    Serial.println(» datchika»);
    }

    void loop()
    {
    // READ DATA
    Serial.print(«DHT22, t»);
    int chk = DHT.read22(DHT22a_PIN);
    switch (chk)
    {
    case DHTLIB_OK:
    Serial.print(«OK,t»);
    break;
    case DHTLIB_ERROR_CHECKSUM:
    Serial.print(«Checksum error,t»);
    break;
    case DHTLIB_ERROR_TIMEOUT:
    Serial.print(«Time out error,t»);
    break;
    default:
    Serial.print(«Unknown error,t»);
    break;
    }

    // DISPLAY DATA

    Serial.print(DHT.humidity, 1);
    Serial.print(«,tt»);
    Serial.print(DHT.temperature, 1);
    Serial.println(» temp1 «);

    // READ DATA второй датчик!!!
    Serial.print(«DHT22, t»);
    int chk2 = DHT.read22(DHT22b_PIN);
    switch (chk)
    {
    case DHTLIB_OK:
    Serial.print(«OK,t»);
    break;
    case DHTLIB_ERROR_CHECKSUM:
    Serial.print(«Checksum error,t»);
    break;
    case DHTLIB_ERROR_TIMEOUT:
    Serial.print(«Time out error,t»);
    break;
    default:
    Serial.print(«Unknown error,t»);
    break;
    }
    // вывод в порт значений с датчика2 — «temp2»

    Serial.print(DHT.humidity, 1);
    Serial.print(«,tt»);
    Serial.print(DHT.temperature, 1);
    Serial.println(» temp2 «);

    delay(3000);// задержка 3сек

    }

  6. библиотека называется Dht11.h. а в коде #include <dht.h>

  7. Вот и пытаюсь нужную найти. Много какие пробовал, ставил dht.h, тоже ошибки выдает.

  8. в архиве есть пример, он точно работает с LCD, ну и библиотека тоже точно рабочая.
    тобиж если библиотека установлена правильно, должно компилироваться.

    инклюдить надо #include <dht11.h>

  9. Так то другие коды с датчиком работают со своими библиотеками. Не работает код на несколько датчиков, для него библиотеку найти не могу.

  10. библиотеке абсолютно не важно с каким количеством датчиков работать.

  11. Это я понимаю. Просто этот код хотел взять за образец и на его основе попробовать сделать свою програму.

  12. int chk2 = DHT.read22(DHT22b_PIN);

    датчик DHT22 или DHT11 ??

Страница 3 из 3

Angel700

Павел

@Angel700

новичок в программирований!

#include "C:UsersUserDocumentsArduinoDHT11.h"
DHT11 DHT(DHT11); // Указать датчик DHT11, DHT21 или DHT22. (несколько датчиков вписывать не нужно)
// Подключать можно только одинаковые датчики, то есть нельзя использовать одновременно DHT11 и DHT22

void setup() 
{
  Serial.begin(57600);
  pinMode(2, INPUT);
  digitalWrite(2, HIGH);
  pinMode(3, INPUT);
  digitalWrite(3, HIGH);
}

void loop() 
{
  int t = DHT.readTemperature(2); // чтение датчика на пине 2
  int h = DHT.readHumidity(2);    // чтение датчика на пине 2
  delay(2000);
  
  Serial.print("Hum: ");
  Serial.print(h);
  Serial.print(" %");
  Serial.print("Temp: ");
  Serial.print(t);
  Serial.println(" C ");
  Serial.print("Hum2: ");
  Serial.print(h2);
  Serial.print(" %");
  Serial.print("Temp2: ");
  Serial.print(t2);
  Serial.println(" C "); 
}

Вот Эта Ошибка
C:UsersUserDocumentsArduinodhTdhT.ino: In function ‘void loop()’:
dhT:16:15: error: request for member ‘readTemperature’ in ‘DHT’, which is of non-class type ‘DHT11(DHT11)’
int t = DHT.readTemperature(2); // чтение датчика на пине 2
^~~~~~~~~~~~~~~
dhT:17:15: error: request for member ‘readHumidity’ in ‘DHT’, which is of non-class type ‘DHT11(DHT11)’
int h = DHT.readHumidity(2); // чтение датчика на пине 2
^~~~~~~~~~~~
dhT:27:16: error: ‘h2’ was not declared in this scope
Serial.print(h2);
^~
C:UsersUserDocumentsArduinodhTdhT.ino:27:16: note: suggested alternative: ‘h’
Serial.print(h2);
^~
h
dhT:30:16: error: ‘t2’ was not declared in this scope
Serial.print(t2);
^~
C:UsersUserDocumentsArduinodhTdhT.ino:30:16: note: suggested alternative: ‘t’
Serial.print(t2);
^~
t
exit status 1
request for member ‘readTemperature’ in ‘DHT’, which is of non-class type ‘DHT11(DHT11)’

Помогите исправить мне эту ошибку


  • Вопрос задан

    более двух лет назад

  • 572 просмотра

Пригласить эксперта

Попробуйте для начала добавить вашу библиотеку в

Менеджер библиотек

и затем подключайте вашу библиотеку из менеджера библиотек

Внимательно разберитесь здесь:

DHT11 DHT(DHT11);

что у вас — имя класса, что — имя экземпляра, а что — константа, которая задефайнена в библиотеке.

Библиотеку установил?
Так пробовал?

#include "stDHT.h"
DHT sens(DHT11);


  • Показать ещё
    Загружается…

09 февр. 2023, в 15:56

20000 руб./за проект

09 февр. 2023, в 15:55

75000 руб./за проект

09 февр. 2023, в 15:13

2000 руб./за проект

Минуточку внимания

This tutorial of Robo India explains how to store and upload the weather data of DHT11 temperature and humidity sensor on cloud ( ThingSpeak.com) using wifi modem NodeMCU.

Detailed Tutorial

1. Introduction:

This tutorial explains how to log weather data on cloud. ThingSpeak.com is to be used as cloud service provider and sensor DHT11 will be used to measure temperature and humidity data.

This tutorial is for NodeMCU on Arduino IDE. Please note that the same tutorial can be performed on LUA as well.

1.2 Hardware required

S.No. Item Quantity
1 NodeMCU  1
2 DHT11 Temperature and Humidity sensor  1
3 Jumper Male to female  3

2. Building Circuit

Make connection as mentioned ahead.

S.NO.          NodeMCU DHT11
 1. Vin VCC
 2. GND GND
 3. D3 Data Out

Circuit Layout:

3. Getting API Key

1. Go to https://thingspeak.com/ and create an account if you do not have one. Login to your account.

2. Create a new channel by clicking on the button.Enter basic details of the channel.Than Scroll down and save the channel.

3. Channel Id is the identity of your channel. Note down this. Than go to API keys copy and paste this key to a separate notepad file will need it later.

4. Programming:

Once the circuit part is done, NodeMCU is needed to be programmed. Here is the code to run this circuit on NodeMCU.

You may download this code (Arduino Sketch) from here.

// Robo India Tutorial 
// Simple code upload the tempeature and humidity data using thingspeak.com
// Hardware: NodeMCU,DHT11

#include <DHT.h>  // Including library for dht

#include <ESP8266WiFi.h>
 
String apiKey = "Your API of thingsspeak";     //  Enter your Write API key from ThingSpeak

const char *ssid =  "Your wifi Network name";     // replace with your wifi ssid and wpa2 key
const char *pass =  "Network password";
const char* server = "api.thingspeak.com";

#define DHTPIN 0          //pin where the dht11 is connected
 
DHT dht(DHTPIN, DHT11);

WiFiClient client;
 
void setup() 
{
       Serial.begin(115200);
       delay(10);
       dht.begin();
 
       Serial.println("Connecting to ");
       Serial.println(ssid);
 
 
       WiFi.begin(ssid, pass);
 
      while (WiFi.status() != WL_CONNECTED) 
     {
            delay(500);
            Serial.print(".");
     }
      Serial.println("");
      Serial.println("WiFi connected");
 
}
 
void loop() 
{
  
      float h = dht.readHumidity();
      float t = dht.readTemperature();
      
              if (isnan(h) || isnan(t)) 
                 {
                     Serial.println("Failed to read from DHT sensor!");
                      return;
                 }

                         if (client.connect(server,80))   //   "184.106.153.149" or api.thingspeak.com
                      {  
                            
                             String postStr = apiKey;
                             postStr +="&field1=";
                             postStr += String(t);
                             postStr +="&field2=";
                             postStr += String(h);
                             postStr += "rnrn";
 
                             client.print("POST /update HTTP/1.1n");
                             client.print("Host: api.thingspeak.comn");
                             client.print("Connection: closen");
                             client.print("X-THINGSPEAKAPIKEY: "+apiKey+"n");
                             client.print("Content-Type: application/x-www-form-urlencodedn");
                             client.print("Content-Length: ");
                             client.print(postStr.length());
                             client.print("nn");
                             client.print(postStr);
 
                             Serial.print("Temperature: ");
                             Serial.print(t);
                             Serial.print(" degrees Celcius, Humidity: ");
                             Serial.print(h);
                             Serial.println("%. Send to Thingspeak.");
                        }
          client.stop();
 
          Serial.println("Waiting...");
  
  // thingspeak needs minimum 15 sec delay between updates, i've set it to 30 seconds
  delay(10000);
}

6. Output

Output of this project is seen on Thingspeak and serial monitor. Open your channel at Thingspeak and output will be shown as mentioned ahead.

Temperature:

Humidity:

On every successful data upload, success message is displayed on serial monitor.

If you have any query please write us at support@roboindia.com

Thanks and Regards
Content Development Team 
Robo India
https://roboindia.com

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
#include <DHT.h>     // подключаем библиотеку для работы с датчиком 
#include <LiquidCrystal.h> // подключаем библиотеку для работы с ЖК дисплеем
LiquidCrystal lcd(7, 6, 5, 4, 3, 2); // какие порты платя сообщаются с контактами дисплея
#define dht_dpin 12 // указываем, с какого порта будет приходить сигнал с датчика
#define dhtTYPE dht11 // инициализация датчика
#define pwm 9 // порт, задействованный на широтно импульсную модуляцию (pulse width modulation)
byte degree[8] = // символ градуса для отображения на ЖК дисплее
{
  0b00011,
  0b00011,
  0b00000,
  0b00000,
  0b00000,
  0b00000,
  0b00000,
  0b00000
};
void setup()
{
  lcd.begin(16, 2); // размер дисплея
  lcd.createChar(1, degree); // создаем "градус"
  lcd.clear(); // очищаем дисплей, курсор в (х=0, у=0)
  lcd.print("   Fan Speed  "); // печать ...
  lcd.setCursor(0, 1); // курсор в (х=0,у=1)
  lcd.print("  Controlling "); //печать ...
  delay(2000); // задежка 2 сек
  analogWrite(pwm, 255); // цикл занятости ШИМ 100%
  lcd.clear(); // очищаем дисплей, курсор в (х=0, у=0)
  lcd.print("PROGRAMIST "); // печать ...
  /*dht.begin();*/
  delay(2000); // задежка 2 сек
}
void loop()
{
  float temp = DHT.readTemperature(); // считываем значение температуры с датчика
  /*dht.read12(dht_dpin); // считываем значение с выхода датчика температуры
    int temp = DHT.temperature; // извлекаем из него температуру*/
  lcd.setCursor(0, 0); // очищаем дисплей, курсор в (х=0, у=0)
  lcd.print("Temperature:"); // печать ...
  lcd.print(temp);   // печать ...
  lcd.write(1);
  lcd.print("C");
  lcd.setCursor(0, 1);
  if (temp < 26 )
  {
    analogWrite(9, 0);
    lcd.print("Fan OFF            ");
    delay(100);
  }
 
  else if (temp == 26)
  {
    analogWrite(pwm, 51);
    lcd.print("Fan Speed: 20%   "); // скорость вращения 20%
    delay(100);
  }
 
  else if (temp == 27)
  {
    analogWrite(pwm, 102);
    lcd.print("Fan Speed: 40%   "); // скорость вращения 40%
    delay(100);
  }
 
  else if (temp == 28)
  {
    analogWrite(pwm, 153);
    lcd.print("Fan Speed: 60%   "); // скорость вращения 60%
    delay(100);
  }
 
  else if (temp == 29)
  {
    analogWrite(pwm, 204);
    lcd.print("Fan Speed: 80%    "); // скорость вращения 80%
    delay(100);
  }
  else if (temp > 29)
  {
    analogWrite(pwm, 255);
    lcd.print("Fan Speed: 100%   "); // скорость вращения 100%
    delay(100);
  }
  delay(3000);
}

In this example we will connect a DHT11 sensor to our Wemos D1, we will then send the temperature and humidity values to thingspeak.

Wemos_D1_ESP8266

DHT11 digital temperature and humidity sensor is a composite Sensor contains a calibrated digital signal output of the temperature and humidity. Application of a dedicated digital modules collection technology and the temperature and humidity sensing technology, to ensure that the product has high reliability and excellent long-term stability. The sensor includes a resistive sense of wet components and an NTC temperature measurement devices, and connected with a high-performance 8-bit microcontroller.

Typically a DHT11 can be bought in a basic breakout board format but can be bought as a standalone part as well, here is a picture of a typical breakout board, this board holds the sensor and a resistor, the resistor is connected between Vdd (3v3) and the signal pin on the board.

dht11 breakout

If you do not use a module like the one aboveyou can build a similar circuit on a breadboard. Here is a typical schematic, which is basically what the breakout above actually is

Dht11_application

You will connect the Gnd of the module (DHt11) to a Gnd on your Wemos board, connect 5v or Vdd of the module (DHt11) to a 3v3 connection on your Wemos and the Sig pin (data pin on the DH11) goes to whatever input you decide to use on your Wemos, in the code below you can see this as

#define DHTPIN 2

You will now need to create a new account at thingspeak – https://thingspeak.com. Once done create a new channel and add two new fields, one will hold the temperature reading and the other will hold the humidity reading from our DHT11. This should look something like this

thingspeak channel

thingspeak channel

Code

You will need an api key from thingspeak.

#include <DHT.h>
#include <ESP8266WiFi.h>
 
// replace with your channel’s thingspeak API key and your SSID and password
String apiKey = "thingspeak api key";
const char* ssid = "ssid name";
const char* password = "ssid password";
const char* server = "api.thingspeak.com";
 
#define DHTPIN D2
#define DHTTYPE DHT11 
 
DHT dht(DHTPIN, DHTTYPE);
WiFiClient client;
 
void setup() 
{
Serial.begin(115200);
delay(10);
dht.begin();
 
WiFi.begin(ssid, password);
 
Serial.println();
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");
 
}
 
void loop() 
{
 
float h = dht.readHumidity();
float t = dht.readTemperature();
if (isnan(h) || isnan(t)) 
{
Serial.println("Failed to read from DHT sensor!");
return;
}
 
if (client.connect(server,80)) {
String postStr = apiKey;
postStr +="&field1=";
postStr += String(t);
postStr +="&field2=";
postStr += String(h);
postStr += "rnrn";
 
client.print("POST /update HTTP/1.1n");
client.print("Host: api.thingspeak.comn");
client.print("Connection: closen");
client.print("X-THINGSPEAKAPIKEY: "+apiKey+"n");
client.print("Content-Type: application/x-www-form-urlencodedn");
client.print("Content-Length: ");
client.print(postStr.length());
client.print("nn");
client.print(postStr);
 
Serial.print("Temperature: ");
Serial.print(t);
Serial.print(" degrees Celsius Humidity: ");
Serial.print(h);
Serial.println("Sending data to Thingspeak");
}
client.stop();
 
Serial.println("Waiting 20 secs");
// thingspeak needs at least a 15 sec delay between updates
// 20 seconds to be safe
delay(20000);
}

Results

If you login to your thingspeak account you can view live channel data, here is an iframe of some data from my test

Hello here,

Before proceeding, if you need to buy DHT11 sensor, check Seeedstudio by clicking here !

In this tutorial we gonna see how to simply use the DHT11 module, It’s a module that can measure ambient temperature 0-50°C and humidity up to 95% RH (Relative humidity), it’s very good for Home Automation projects or DIY projects for daily use.

Also there are a lot of modules that have the same function as this one, you can check them here:

  • Measure temperature/humidity using DHT22 + LCD i2c + Arduino
  • Measure Temperature / Humidity and Heat Index using DHT 21 (AM 2301) + Arduino + LCD
  • Measuring temperature and humidity using AM2320 (DHT12 ??) i2c sensor
  • SHT 21/HTU 21 – Measure Temperature and Himidity with Arduino + OLED/LCD [DigitSpace.com]

For this we gonna need:

  • DHT 11 (obvious 😃 ) note here that I’m using 3 pins version there are 4 pins one.

2 Versions of DHT11 sensor
  • Arduino board here I’ll use Uno
  • LCD i2c screen
  • Breadboard and jump wires

The LCD i2c is totally optional but usually used with this module as a classic learning project, in case you don’t know how to use one check here:LCD i2c tutorial.

The LCD I used is a I2C version, there are the standard versions but they require a lot of pins, and also in this case you’ll need another library and code functions.

Wiring:

DHT11 (3 pins version) wired with LCD i²c and an Arduino

Libraries:

DHT library: Download library here

LCD i2c New_Liquid_Crystal library: Download LCD i2c library here

Codes

You can download the codes: Download codes here or check below:

Code 1:

The code 1 works with the Serial monitor, it shows the ambient temperature in °C and humidity in %RH, and refresh every 1s.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

#include <dht.h> //DHT library

dht DHT; //Declaring dht entity named DHT

#define DHT11_PIN 7 //DHT data pin

void setup(){

  Serial.begin(9600);

}

void loop()

{

  int chk = DHT.read11(DHT11_PIN); //Read data temperature from DHT11 pin

  Serial.print(«Temperature = «);  //Show ambient temperature and humidity every 1s

  Serial.println(DHT.temperature);

  Serial.print(«Humidity = «);

  Serial.println(DHT.humidity);

  delay(1000);

}

Code2:

The second code works with LCD i²c screen, it shows both temperature and humidity over there.

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

//This code is to use with DHT11 Temperature/humidity sensor with LCD i2c screen

//We measure the values of the temperature and humidity then print them on the screen every second

//Refer to Surtrtech channel on youtube or blogger for more information or how to use the LCD i2c

#include <dht.h> //DHT and LCD libraries

#include <LiquidCrystal_I2C.h>

#define I2C_ADDR 0x27

#define BACKLIGHT_PIN 3

#define En_pin 2

#define Rw_pin 1

#define Rs_pin 0

#define D4_pin 4

#define D5_pin 5

#define D6_pin 6

#define D7_pin 7

LiquidCrystal_I2C lcd(I2C_ADDR,En_pin,Rw_pin,Rs_pin,D4_pin,D5_pin,D6_pin,D7_pin);

dht DHT; //Declaring the DHT as a dht type to use it later

#define DHT11_PIN 7 //Declaring where the DHT signal pin is wired

void setup(){

  lcd.begin (16,2);

  lcd.setBacklightPin(BACKLIGHT_PIN,POSITIVE);

  lcd.setBacklight(HIGH);

  lcd.home ();

}

void loop()

{

  lcd.clear();

  lcd.setCursor(0,0);

  int chk = DHT.read11(DHT11_PIN); //Reading data from the module

  lcd.print(«Temp: «);

  lcd.print(DHT.temperature); //Showing temperature value (before that you can do some math to get the temperature in Farnheit)

  lcd.print(» C»);

  lcd.setCursor(0,1);

  lcd.print(«Humidity: «);

  lcd.println(DHT.humidity); //Showing humidity percentage

  lcd.print(» %»);

  delay(1000); //Refreshing every 1s

}

Categories

Non classé

Tags

Arduino, dht, diy, electronics, humidity, i2c, Lcd, measure, module, science, sensor, technology, temperature, tutorial, wiring

Yassine View All

Automation and Electrical Engineer, Electronics amateur trying to share my little projects.

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Error devicenotificationsubscribe ukeysoft
  • Error device unauthorized please check the confirmation dialog on your device
  • Error device unauthorized adb что делать
  • Error device reset 0 result 8876086c
  • Error device removed please restart the game

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии