Connecting ESP32 with DHT11 sensor and displaying data

Reading time: 2 min.

In previous articles, we combined the ESP32 with a simple DS18B20 temperature sensor and an OLED display, which also displayed the data received from the sensor. We also created a simple web server that displayed the data from the temperature sensor. In this tutorial, we will use the knowledge gained in the previous articles and create a project that displays data from the DHT11 temperature and humidity sensor on an OLED display and a web page.

What will you need to create the project?

In order to complete this connection, we will need an ESP32 module, a DHT11 sensor and an OLED display – but you have probably figured as much. All necessary components can be found in a specially prepared kit with the ESP32 module.

The full list of components used is below.

Connecting components to a contact plate

The OLED display uses the I2C interface for communication and was connected to pins 21 (SDA) and 22 (SCK) of the ESP32 module, while the DHT11 sensor was connected to pin 18 using a 4.7 kΩ resistor. Below is a diagram of how the modules are connected to the ESP32.


 data-lazy-srcset=


 data-lazy-srcset=

Required libraries for OLED and DHT11

In order to properly operate the display with the SH1106 controller and the DHT11 sensor, you need to install the appropriate libraries in the Arduino IDE environment. The required libraries can be found at the links:

Additionally, you will need libraries to create an ESP32 server:

Downloaded as a .zip package, install the libraries in the Arduino IDE environment.

 data-lazy-srcset=

A window will appear where you search for the location of the downloaded packages, then select the .zip library and select the Open button.

Programming ESP32 module

After properly connecting the modules to the ESP32 and uploading the libraries for the OLED display, DHT11 and ESP32 server. The following code will display data from the DHT11 sensor on the OLED screen and create a simple web server, also with data from the sensor.

					#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SH1106.h>
#include "WiFi.h"
#include "ESPAsyncWebServer.h"
#include <Adafruit_Sensor.h>
#include <DHT.h>
//Enter the details of the WiFi network you wish to connect to
const char* ssid = "Botland_dev-24G";
const char* password = "botl4nd2020";
//Define the ESP pins to which the display is connected
#define OLED_SDA 21
#define OLED_SCL 22
Adafruit_SH1106 display(21, 22);
//Define the ESP pin to which DH11 is connected
#define DHTPIN 18
//Select the type of sensor used (DHT11)
#define DHTTYPE    DHT11
DHT dht(DHTPIN, DHTTYPE);
//Create an AsyncWebServer object on port 80
AsyncWebServer server(80);
//Read temperature from DHT11
String readDHTTemperature() {
  float t = dht.readTemperature();
  if (isnan(t)) {
    Serial.println("Temperature measurement error");
    return "--";
  }
  else {
    Serial.println(t);
    return String(t);
  }
}
//Read the humidity from DHT11
String readDHTHumidity() {
  float h = dht.readHumidity();
  if (isnan(h)) {
    Serial.println("Humidity measurement error");
    return "--";
  }
  else {
    Serial.println(h);
    return String(h);
  }
}
//Create an HTML page layout
const char index_html[] PROGMEM = R"rawliteral(
<!DOCTYPE HTML><html>
<head>
  <meta name="vewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
  <style>
    html {
     font-family: Arial;
     display: inline-block;
     margin: 0px auto;
     text-align: center;
    }
    h2 {font-size: 3.0rem;}
    p {font-size: 3.0rem;}
    .units {font-size: 1.2rem;}
    .dht-labels{
     font-size: 1.5rem;
     vertical-align: middle;
     padding-bottom: 15px;
    }
    </style>
</head>
<body>
  <h2><span id="ESP32-Server">ESP32 Server</span></h2>
  <p>
    Temperature
    %TEMPERATURE%
    <sup>&deg;C</sup>
  </p>
  <p>
    Humidity
    <sup>&percnt;</sup>
  </p>
<script>class RocketElementorAnimation{constructor(){this.deviceMode=document.createElement("span"),this.deviceMode.id="elementor-device-mode-wpr",this.deviceMode.setAttribute("class","elementor-screen-only"),document.body.appendChild(this.deviceMode)}_detectAnimations(){let t=getComputedStyle(this.deviceMode,":after").content.replace(/"/g,"");this.animationSettingKeys=this._listAnimationSettingsKeys(t),document.querySelectorAll(".elementor-invisible[data-settings]").forEach(t=>{const e=t.getBoundingClientRect();if(e.bottom>=0&&e.top<=window.innerHeight)try{this._animateElement(t)}catch(t){}})}_animateElement(t){const e=JSON.parse(t.dataset.settings),i=e._animation_delay||e.animation_delay||0,n=e[this.animationSettingKeys.find(t=>e[t])];if("none"===n)return void t.classList.remove("elementor-invisible");t.classList.remove(n),this.currentAnimation&&t.classList.remove(this.currentAnimation),this.currentAnimation=n;let s=setTimeout(()=>{t.classList.remove("elementor-invisible"),t.classList.add("animated",n),this._removeAnimationSettings(t,e)},i);window.addEventListener("rocket-startLoading",function(){clearTimeout(s)})}_listAnimationSettingsKeys(t="mobile"){const e=[""];switch(t){case"mobile":e.unshift("_mobile");case"tablet":e.unshift("_tablet");case"desktop":e.unshift("_desktop")}const i=[];return["animation","_animation"].forEach(t=>{e.forEach(e=>{i.push(t+e)})}),i}_removeAnimationSettings(t,e){this._listAnimationSettingsKeys().forEach(t=>delete e[t]),t.dataset.settings=JSON.stringify(e)}static run(){const t=new RocketElementorAnimation;requestAnimationFrame(t._detectAnimations.bind(t))}}document.addEventListener("DOMContentLoaded",RocketElementorAnimation.run);</script></body>
</html>)rawliteral";
String processor(const String& var) {
  if (var == "TEMPERATURE") {
    return readDHTTemperature();
  }
  else if (var == "HUMIDITY") {
    return readDHTHumidity();
  }
  return String();
}
void setup() {
  Serial.begin(115200);
  display.begin(SH1106_SWITCHCAPVCC, 0x3C);
  display.clearDisplay();
  display.display();
  dht.begin();
  //Connecting to WiFi
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi..." );
  }
  //Display the local IP address of the ESP32 module
  Serial.println(WiFi.localIP());
  server.on("/", HTTP_GET, [](AsyncWebServerRequest * request) {
    request->send_P(200, "text/html", index_html, processor);
  });
  server.on("/temperature", HTTP_GET, [](AsyncWebServerRequest * request) {
    request->send_P(200, "text/plain", readDHTTemperature().c_str());
  });
  server.on("/humidity", HTTP_GET, [](AsyncWebServerRequest * request) {
    request->send_P(200, "text/plain", readDHTHumidity().c_str());
  });
  server.begin();
}
void loop() {
  float t = dht.readTemperature();
  float h = dht.readHumidity();
  //Wypisanie danych na ekranie OLED
  display.setTextColor(WHITE);
  display.setCursor(0, 0);
  display.setTextSize(1);
  display.println("Temperature");
  display.print(t);
  display.cp437(true);
  display.write(167);
  display.println("C");
  display.display();
  display.setCursor(0, 30);
  display.setTextSize(1);
  display.println("Humidity");
  display.setTextSize(1);
  display.print(h);
  display.println("%");
  display.display();
  display.clearDisplay();
  delay(5000);
}

				
			

Once the code has been correctly uploaded to the ESP32 module, the serial monitor will display the IP address of your ESP32 server and the display will show the measurement data from the sensor.

 data-lazy-srcset=
 data-lazy-srcset=

How useful was this post?

Click on a star to rate it!

Average rating 5 / 5. Vote count: 1

No votes so far! Be the first to rate this post.

Share:

Picture of Oskar Pacelt

Oskar Pacelt

Fan dobrej literatury i muzyki. Wierzy, że udany tekst jest jak list wysłany w przyszłość. W życiu najbardziej interesuje go prawda, pozostałych zainteresowań zliczyć nie sposób. Kocha pływać.

See more:

Leave a Reply

Your email address will not be published. Required fields are marked *

For security, use of Google's reCAPTCHA service is required which is subject to the Google Privacy Policy and Terms of Use.