• Skip to main content
  • Skip to primary sidebar

RNTLab.com

The Ultimate Shortcut to Learn Electronics and Programming with Open Source Hardware and Software

  • Courses
  • Forum
    • Forum
    • Ask Question
  • Shop
  • Account
  • Blog
  • Login

An ESP32 tutorial: Mix of ordering two relays and reading a DHT22

Q&A Forum › Category: ESP32 › An ESP32 tutorial: Mix of ordering two relays and reading a DHT22
0 Vote Up Vote Down
Charles ROUX asked 5 years ago

Auto translated:

“Hello my dear RUI Santos

I asked a question yesterday about mixing two tutorials from your ESP32 book

I want to read a DHT22 and order two relays

you did not have time to answer me in the meantime I started mixing the two tutorials

it works but on two different screens with two addresses 192.168.1.50:8000 and 192.168.1.50:9000

I can not have on the same screen the two control relays and the display of DHT22

attached the program

can you give me some advice ???”

Original

Bonjour mon cher RUI Santos

j’ai posé une question hier concernant le mélange de deux tutoriels de ton livre ESP32

je veux lire un DHT22 et commander deux relays

tu n’a pas eu le temps de me répondre en attendant j’ai commencé le mélange des deux tutoriels

cela fonctionne mais sur deux écrans différent avec deux adresse 192.168.1.50:8000 et 192.168.1.50:9000

je n’arrive pas à avoir sur le même écran les deux commande des relays et l’affichage du DHT22

ci-joint le programme

peux tu me donner un conseil ???

/*********
Rui Santos
Complete project details at https://randomnerdtutorials.com
Wifi_Web_Server_DHT.ino
22-04-2020 18h00
cmd de deux relays et d'un DHT22 T° et H%
deux serveur un en port 8000 et l'autre en port 9000
// Create AsyncWebServer object on port 80
AsyncWebServer server1(8000);
// Set web server port number to 80
WiFiServer server2(9000);
*********/
// Import required libraries
#include "WiFi.h"
#include <WiFi.h>
#include "ESPAsyncWebServer.h"
#include <Adafruit_Sensor.h>
#include <DHT.h>
// Replace with your network credentials
const char* ssid = "RCH-B5B0-A";
const char* password = "VZJDNFJ4jHapWTGYda";
#define DHTPIN 4 // Digital pin connected to the DHT22 sensor
// Uncomment the type of sensor in use:
#define DHTTYPE DHT22 // DHT 22 (AM2302)
// definition des variable h et t Temperature et humidite pour les fonction de lecture
const float t = 0;
const float h = 0;
// Create AsyncWebServer object on port 80
AsyncWebServer server1(8000);
// Set web server port number to 80
WiFiServer server2(9000);
// Variable to store the HTTP request
String header;
// Auxiliar variables to store the current output state
String outputAState = "off";
String outputBState = "off";
// Assign output variables to GPIO pins
const int outputA = 26;
const int outputB = 27;
DHT dht(DHTPIN, DHTTYPE);

// lecture de la temperature
String readDHTTemperature() {
// Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
// Read temperature as Celsius (the default)
float t = dht.readTemperature();
// Check if any reads failed and exit early (to try again).
if (isnan(t)) {
Serial.println("Failed to read from DHT22 sensor!");
return "--";
}
else {
Serial.println(t);
return String(t);
}
}
//Lecture de l Humidite
String readDHTHumidity() {
// Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
float h = dht.readHumidity();
if (isnan(h)) {
Serial.println("Failed to read from DHT22 sensor!");
return "--";
}
else {
Serial.println(h);
return String(h);
}
}
// affichage de la page HTML
const char index_html[] PROGMEM = R"rawliteral(
<!DOCTYPE HTML><html>
<head>
<meta name="viewport" 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>ESP32 DHT22 Server</h2>
<p>
<i class="fas fa-thermometer-half" style="color:#059e8a;"></i>
<span class="dht-labels">Temperature</span>
<span id="temperature">%TEMPERATURE%</span>
<sup class="units">&deg;C</sup>
</p>
<p>
<i class="fas fa-tint" style="color:#00add6;"></i>
<span class="dht-labels">Humidity</span>
<span id="humidity">%HUMIDITY%</span>
<sup class="units">%</sup>
</p>
</body>
<script>
setInterval(function ( )
{
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function()
{
if (this.readyState == 4 && this.status == 200)
{
document.getElementById("temperature").innerHTML = this.responseText;
}
};
xhttp.open("GET", "/temperature", true);
xhttp.send();
}, 10000 ) ;
setInterval(function ( )
{
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200)
{
document.getElementById("humidity").innerHTML = this.responseText;
}
};
xhttp.open("GET", "/humidity", true);
xhttp.send();
}, 10000 ) ;
</script>
</html>)rawliteral";
// Remplace l'espace reserve par des valeurs DHT
String processor(const String& var)
{
//Serial.println(var);
if(var == "TEMPERATURE")
{
return readDHTTemperature();
}
else if(var == "HUMIDITY"){
return readDHTHumidity();
}
return String();
}
void setup(){
// Serial port for debugging purposes
Serial.begin(115200);
// Initialize the output variables as outputs
pinMode(outputA, OUTPUT);
pinMode(outputB, OUTPUT);

// Set outputs to LOW
digitalWrite(outputA, HIGH);
digitalWrite(outputB, HIGH);
dht.begin();
// Connect to Wi-Fi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) 
{
delay(1000);
Serial.println("Attente Connexion au WiFi..");
delay(1500);
Serial.print(".");
}
// Print ESP32 Local IP Address
// Print local IP address and start web server
Serial.println("");
Serial.println("WiFi connected.");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());

// Start server
server1.begin();
server2.begin();
// Route for root / web page
server1.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
request->send_P(200, "text/html", index_html, processor);
});
server1.on("/temperature", HTTP_GET, [](AsyncWebServerRequest *request){
request->send_P(200, "text/plain", readDHTTemperature().c_str());
});
server1.on("/humidity", HTTP_GET, [](AsyncWebServerRequest *request){
request->send_P(200, "text/plain", readDHTHumidity().c_str());
});
}
void loop()
{
WiFiClient client2 = server2.available(); // Listen for incoming clients
if (client2) { // If a new client connects,
Serial.println("New client2."); // print a message out in the serial port
String currentLine = ""; // make a String to hold incoming data from the client
while (client2.connected()) { // loop while the client's connected
if (client2.available()) { // if there's bytes to read from the client,
char c = client2.read(); // read a byte, then
Serial.write(c); // print it out the serial monitor
header += c;
if (c == '\n') { // if the byte is a newline character
// if the current line is blank, you got two newline characters in a row.
// that's the end of the client HTTP request, so send a response:
if (currentLine.length() == 0) {
// HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
// and a content-type so the client knows what's coming, then a blank line:
client2.println("HTTP/1.1 200 OK");
client2.println("Content-type:text/html");
client2.println("Connection: close");
client2.println();

// turns the GPIOs on and off
if (header.indexOf("GET /A/on") >= 0) {
Serial.println("GPIO A6 on");
outputAState = "on";
digitalWrite(outputA, LOW);
} else if (header.indexOf("GET /A/off") >= 0) {
Serial.println("GPIO A off");
outputAState = "off";
digitalWrite(outputA, HIGH);
} else if (header.indexOf("GET /B/on") >= 0) {
Serial.println("GPIO B on");
outputBState = "on";
digitalWrite(outputB, LOW);
} else if (header.indexOf("GET /B/off") >= 0) {
Serial.println("GPIO B off");
outputBState = "off";
digitalWrite(outputB, HIGH);
}

// Display the HTML web page
client2.println("<!DOCTYPE html><html>");
client2.println("<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
client2.println("<link rel=\"icon\" href=\"data:,\">");
// CSS to style the on/off buttons 
// Feel free to change the background-color and font-size attributes to fit your preferences
client2.println("<style>html { font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: center;}");
client2.println(".button { background-color: #4CAF50; border: none; color: white; padding: 16px 40px;");
client2.println("text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}");
client2.println(".button2 {background-color: #555555;}</style></head>");

// Web Page Heading
client2.println("<body><h1>ESP32 Web Server</h1>");

// Display current state, and ON/OFF buttons for GPIO A 
client2.println("<p>GPIO A - State " + outputAState + "</p>");
// If the outputAState is off, it displays the ON button 
if (outputAState=="off") {
client2.println("<p><a href=\"/A/on\"><button class=\"button\">ON</button></a></p>");
} else {
client2.println("<p><a href=\"/A/off\"><button class=\"button button2\">OFF</button></a></p>");
}

// Display current state, and ON/OFF buttons for GPIO B 
client2.println("<p>GPIO B - State " + outputBState + "</p>");
// If the outputBState is off, it displays the ON button 
if (outputBState=="off") {
client2.println("<p><a href=\"/B/on\"><button class=\"button\">ON</button></a></p>");
} else {
client2.println("<p><a href=\"/B/off\"><button class=\"button button2\">OFF</button></a></p>");
}
client2.println("</body></html>");

// The HTTP response ends with another blank line
client2.println();
// Break out of the while loop
break;
} else { // if you got a newline, then clear currentLine
currentLine = "";
}
} else if (c != '\r') { // if you got anything else but a carriage return character,
currentLine += c; // add it to the end of the currentLine
}
}
}
// Clear the header variable
header = "";
// Close the connection
client2.stop();
Serial.println("client2 disconnected.");
Serial.println("");
}
}
2 Answers
0 Vote Up Vote Down
Sara Santos Staff answered 5 years ago

Hi Charles.
I’m sorry, but my knowledge in French is pretty limited.
I’ve used translator to read your question. In further questions try to post in English.
Can you provide more details about what you want to do?
You want to control GPIOs and display sensor readings on the same web server?
I didn’t understand if you want to have everything on the same page or in different pages.
Regards,
Sara

0 Vote Up Vote Down
Sara Santos Staff answered 5 years ago

You can build your web server using just the AsyncWeb server library.
This unit shows how to create ON/OFF buttons using the AsyncWeb server library: https://rntlab.com/module-12/build-an-esp32-web-server-using-files-from-filesystem-spiffs/
It saves the files in SPIFFS. But you can load the HTML and CSS on the Arduino code if you prefer.
Take a look at that code and try to put it together with the temperature web server.
After that, let me know if you need further help.
Regards,
Sara
 

Primary Sidebar

Login to Ask or Answer Questions

This Forum is private and it’s only available for members enrolled in our Courses.

Login »

Latest Course Updates

  • [New Edition] Build ESP32-CAM Projects eBook – 2nd Edition April 16, 2025
  • [eBook Updated] Learn ESP32 with Arduino IDE eBook – Version 3.2 April 16, 2025

You must be logged in to view this content.

Contact Support - Refunds - Privacy - Terms - MakerAdvisor.com - Member Login

Copyright © 2013-2025 · RandomNerdTutorials.com · All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.