Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*********
- title : ESP32_DHT_NTP_Clock_LCD2004
- target : ESP32 Dev Module
- ESP32 pinout
- LCD1602 display on I2C
- author : Patrick Dubois
- license : public domain
- *********/
- // Import required libraries
- // if the library is global use <>
- // if the library is local use ""
- #include <ArduinoOTA.h>
- #include <AsyncTCP.h>
- #include <DHT.h>
- #include <ESPmDNS.h>
- #include <ESPAsyncWebServer.h>
- #include <LiquidCrystal_I2C.h>
- #include <time.h>
- #include <WiFi.h>
- #include <Wire.h>
- #include "html_js.html"
- #include "STAcredentials.h"
- #define button0Pin 0 // GPIO 0 or PRG button
- #define BuiltInLed 2 // GPIO led allumée par erreur dans la boucle Wifi not connected ?
- #define tempo 1000 // 1 seconde
- #define tempo1 60000 // 1 minute
- #define baudrateSerial 115200 // vitesse communication Arduino - PC
- #define SCL_GPIO 32
- #define SDA_GPIO 33
- #define numCols 20 // for lcd
- #define numRows 4
- LiquidCrystal_I2C lcd(0x27, numCols, numRows); // use this for I2C LCD.
- #define DHTPin1 26 // GPIO used for the DHT sensor
- #define DHTPin2 27 // GPIO used for the DHT sensor
- #define DHTPin3 14 // GPIO used for the DHT sensor
- #define DHTType1 DHT11 // DHT 11 // from left to right : data vcc gnd
- #define DHTType2 DHT22 // DHT 22 (AM2302), AM2321 // from left to right : vcc data gnd
- DHT dht[] = { DHT(DHTPin1, DHT22),
- DHT(DHTPin2, DHT22),
- DHT(DHTPin3, DHT11)};
- // Create AsyncWebServer object on port 8092 instead of 80 already used on the network
- AsyncWebServer server(8092);
- #define ntpServer "europe.pool.ntp.org"
- char dtDateTime[21];
- bool bLCDDisplay = false;
- bool bButton0Pressed = false;
- bool bInit = true;
- byte nIndex = 0;
- uint32_t newMillis, oldMillis, oldMillis1;
- const uint32_t webDuration = 1000 * 60 * 1; // was 60 sec duration for web update, now 1 minute
- // function prototype declarations
- void Display_Init(void);
- void DisplayIMessage(String sMessage, bool bClear, bool bCRLN);
- void OTA_Init(void);
- String processor(const String& var);
- String readDHTTemperature(byte nIndex);
- String readDHTHumidity(byte nIndex);
- String readLocalTime(void);
- int WiFi_Init(byte nIndex);
- // end declarations
- void IRAM_ATTR onButton0Event() {
- bButton0Pressed = true;
- }
- void setup() {
- btStop();
- Wire.begin(SDA_GPIO, SCL_GPIO);
- Serial.begin(baudrateSerial); // Serial0
- for (auto& sensor : dht) { // https://forum.arduino.cc/t/multiple-dht22-sensors/525773/4
- sensor.begin();
- }
- Display_Init();
- oldMillis = oldMillis1 = newMillis = millis();
- WiFi_Init(nIndex);
- OTA_Init();
- configTzTime("CET-1CEST,M3.5.0,M10.5.0/3", ntpServer); // "Europe/Paris","CET-1CEST,M3.5.0,M10.5.0/3"
- // https://raw.githubusercontent.com/nayarsystems/posix_tz_db/master/zones.csv
- pinMode(BuiltInLed, OUTPUT);
- digitalWrite(BuiltInLed, LOW); // ON after Wifi connection so I set it OFF
- pinMode(button0Pin, INPUT_PULLDOWN); // GPIO 0
- attachInterrupt(digitalPinToInterrupt(button0Pin), onButton0Event, RISING);
- // Route for root / web page
- server.on("/", HTTP_GET, [](AsyncWebServerRequest * request) {
- request->send_P(200, "text/html", index_html, processor);
- });
- server.on("/temperature0", HTTP_GET, [](AsyncWebServerRequest * request) {
- request->send_P(200, "text/plain", readDHTTemperature(0).c_str());
- });
- server.on("/humidity0", HTTP_GET, [](AsyncWebServerRequest * request) {
- request->send_P(200, "text/plain", readDHTHumidity(0).c_str());
- });
- server.on("/temperature1", HTTP_GET, [](AsyncWebServerRequest * request) {
- request->send_P(200, "text/plain", readDHTTemperature(1).c_str());
- });
- server.on("/humidity1", HTTP_GET, [](AsyncWebServerRequest * request) {
- request->send_P(200, "text/plain", readDHTHumidity(1).c_str());
- });
- server.on("/temperature2", HTTP_GET, [](AsyncWebServerRequest * request) {
- request->send_P(200, "text/plain", readDHTTemperature(2).c_str());
- });
- server.on("/humidity2", HTTP_GET, [](AsyncWebServerRequest * request) {
- request->send_P(200, "text/plain", readDHTHumidity(2).c_str());
- });
- server.on("/date_time", HTTP_GET, [](AsyncWebServerRequest * request) {
- request->send_P(200, "text/plain", readLocalTime().c_str());
- });
- // Start server
- server.begin();
- }
- // Replaces placeholder with BME values
- String processor(const String& var) {
- // Serial.println(var);
- if (var == "TEMPERATURE0") {
- return readDHTTemperature(0);
- }
- else if (var == "HUMIDITY0") {
- return readDHTHumidity(0);
- }
- else if (var == "TEMPERATURE1") {
- return readDHTTemperature(1);
- }
- else if (var == "HUMIDITY1") {
- return readDHTHumidity(1);
- }
- else if (var == "TEMPERATURE2") {
- return readDHTTemperature(2);
- }
- else if (var == "HUMIDITY2") {
- return readDHTHumidity(2);
- }
- else if (var == "DATE_TIME") {
- return readLocalTime();
- }
- return String();
- }
- void loop() {
- String sString;
- static char sBuffer[24];
- ArduinoOTA.handle();
- newMillis = millis();
- if (bButton0Pressed) {
- nIndex = nIndex < 3 ? ++nIndex : 0;
- bButton0Pressed = false;
- detachInterrupt(digitalPinToInterrupt(button0Pin));
- WiFi_Init(nIndex);
- bInit = true;
- attachInterrupt(digitalPinToInterrupt(button0Pin), onButton0Event, RISING);
- }
- if (newMillis > oldMillis + tempo) {
- oldMillis = newMillis;
- sString = readLocalTime();
- lcd.setCursor(0, 3); // cols, rows
- lcd.print(sString);
- }
- if ((newMillis > oldMillis1 + tempo1) || bInit) {
- oldMillis1 = newMillis;
- bInit = false;
- // to have the degree and percent caracter https://www.letscontrolit.com/forum/viewtopic.php?t=2368
- for (byte nIndex = 0; nIndex < 3; nIndex++) {
- sprintf(sBuffer,"Capt.%d %s%c %s%c", nIndex+1, readDHTTemperature(nIndex), byte(223), readDHTHumidity(nIndex), byte(37));
- lcd.setCursor(0, nIndex); lcd.print(sBuffer);
- }
- }
- }
- String readLocalTime() {
- struct tm timeinfo;
- if (getLocalTime(&timeinfo)) {
- strftime(dtDateTime, sizeof(dtDateTime), "%H:%M.%S %d/%m/%Y", &timeinfo);
- }
- return dtDateTime;
- }
- String readDHTTemperature(byte nIndex) {
- // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
- // Read temperature as Celsius (the default)
- // Read temperature as Fahrenheit (isFahrenheit = true)
- float t;
- String sResult = "--";
- t = dht[nIndex].readTemperature();
- if (!(isnan(t))) {
- sResult = String(t);
- }
- return sResult;
- }
- String readDHTHumidity(byte nIndex) {
- float h;
- String sResult = "--";
- h = dht[nIndex].readHumidity();
- if (!(isnan(h))) {
- sResult = String(h);
- }
- return sResult;
- }
- int WiFi_Init(byte nIndex) {
- int iResult = 0;
- String SSID_NAME = WifiID[nIndex][0];
- DisplayIMessage("Connecting to", true, true);
- DisplayIMessage(SSID_NAME, false, true );
- WiFi.setHostname(HOSTNAME);
- WiFi.begin(SSID_NAME, WifiID[nIndex][1]); // Password
- while (WiFi.status() != WL_CONNECTED) {
- delay(500);
- DisplayIMessage(".", false, false);
- if (millis() > newMillis + 5000) {
- iResult = -1;
- break;
- }
- }
- lcd.clear();
- return iResult;
- }
- void Display_Init() {
- lcd.init(); // I2C LCD init command
- bLCDDisplay = true;
- lcd.backlight(); // I2C LCD turn backlight on
- //lcd.setCursor(6, 0); lcd.print(HOSTNAME);
- delay(2000);
- }
- void DisplayIMessage(String sMessage, bool bClear, bool bCRLN) {
- static int nRow = 0;
- if (bLCDDisplay) {
- if (bClear) {
- lcd.clear();
- lcd.setCursor(0, nRow=0);
- }
- if (bCRLN) {
- lcd.setCursor(0, nRow++);
- lcd.print(sMessage);
- }
- else
- lcd.print(sMessage);
- }
- else
- Serial.println(sMessage);
- }
- void OTA_Init(){
- // Port defaults to 3232
- // ArduinoOTA.setPort(3232);
- // Hostname defaults to esp3232-[MAC]
- ArduinoOTA.setHostname(HOSTNAME);
- // No authentication by default
- // ArduinoOTA.setPassword("admin");
- ArduinoOTA.setPassword(PASSWORD);
- // Password can be set with it's md5 value as well
- // MD5(admin) = 21232f297a57a5a743894a0e4a801fc3
- // ArduinoOTA.setPasswordHash("21232f297a57a5a743894a0e4a801fc3");
- ArduinoOTA
- .onStart([]() {
- String type;
- if (ArduinoOTA.getCommand() == U_FLASH)
- type = "sketch";
- else // U_SPIFFS
- type = "filesystem";
- // NOTE: if updating SPIFFS this would be the place to unmount SPIFFS using SPIFFS.end()
- Serial.println("Start updating " + type);
- })
- .onEnd([]() {
- Serial.println("\nEnd");
- })
- .onProgress([](unsigned int progress, unsigned int total) {
- Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
- })
- .onError([](ota_error_t error) {
- Serial.printf("Error[%u]: ", error);
- if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed");
- else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed");
- else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed");
- else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed");
- else if (error == OTA_END_ERROR) Serial.println("End Failed");
- });
- ArduinoOTA.begin();
- }
- /* *********************************************
- /* to extract and name STAcredentials.h
- ***********************************************/
- #define HOSTNAME "ESP32_DHT_WebServer"
- #define PASSWORD "12345678"
- String WifiID[4][2]= { { "Mankell","password_to_change"},
- { "Box2", "password_to_change"},
- { "Box3", "password_to_change"},
- { "Box4", "password_to_change"}};
- /* **********************************************
- /* to extract and name html_js.html
- /* html page conception and scripts
- ************************************************/
- const char index_html[] PROGMEM = R"rawliteral(
- <!DOCTYPE HTML><html>
- <head>
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <meta charset="utf-8">
- <meta http-equiv="refresh" content="60">
- <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
- <style>
- html {
- font-family: Arial;
- display: inline-block;
- margin: 0px auto;
- text-align: center;
- }
- h2 { font-size: 3.0rem; }
- p { font-size: 3.0rem;}
- .ref { font-size: 1.0rem; }
- .units { font-size: 1.2rem; }
- .bme-labels{
- font-size: 1.5rem;
- text-align: left;
- vertical-align:middle;
- padding-bottom: 15px;
- }
- </style>
- </head>
- <body>
- <h2>Esp32 DHT Server</h2>
- <p>
- <i class="fas fa-thermometer-half" style="color:#059e8a;"></i>
- <span class="bme-labels">Température 1</span>
- <span id="temperature0">%TEMPERATURE0%</span>
- <sup class="units">°C</sup>
- </p>
- <p>
- <i class="fas fa-tint" style="color:#00add6;"></i>
- <span class="bme-labels">Humidité 1</span>
- <span id="humidity0">%HUMIDITY0%</span>
- <sup class="units">%</sup>
- </p>
- <p>
- <i class="fas fa-temperature-half" style="color:#059e8a;"></i>
- <span class="bme-labels">Température 2</span>
- <span id="temperature1">%TEMPERATURE1%</span>
- <sup class="units">°C</sup>
- </p>
- <p>
- <i class="fas fa-tint" style="color:#00add6;"></i>
- <span class="bme-labels">Humidité 2</span>
- <span id="humidity1">%HUMIDITY1%</span>
- <sup class="units">%</sup>
- </p>
- <p>
- <i class="fas fa-temperature-half" style="color:#059e8a;"></i>
- <span class="bme-labels">Température 3</span>
- <span id="temperature2">%TEMPERATURE2%</span>
- <sup class="units">°C</sup>
- </p>
- <p>
- <i class="fas fa-tint" style="color:#00add6;"></i>
- <span class="bme-labels">Humidité 3</span>
- <span id="humidity2">%HUMIDITY2%</span>
- <sup class="units">%</sup>
- </p>
- <p>
- <i class="fas fa-clock"></i>
- <span class="bme-labels">Relevé le</span>
- <span id="date_time" class="bme-labels">%DATE_TIME%</span>
- <!-- sup class="ref">UTC</sup -->
- </p>
- </body>
- <script>
- setInterval(function () {
- var xhttp = new XMLHttpRequest();
- xhttp.onreadystatechange = function() {
- if (this.readyState == 4 && this.status == 200) {
- document.getElementById("temperature1").innerHTML = this.responseText;
- }
- };
- xhttp.open("GET", "/temperature1", true);
- xhttp.send();
- }, webDuration ) ;
- setInterval(function () {
- var xhttp = new XMLHttpRequest();
- xhttp.onreadystatechange = function() {
- if (this.readyState == 4 && this.status == 200) {
- document.getElementById("humidity1").innerHTML = this.responseText;
- }
- };
- xhttp.open("GET", "/humidity1", true);
- xhttp.send();
- }, webDuration ) ;
- setInterval(function () {
- var xhttp = new XMLHttpRequest();
- xhttp.onreadystatechange = function() {
- if (this.readyState == 4 && this.status == 200) {
- document.getElementById("temperature2").innerHTML = this.responseText;
- }
- };
- xhttp.open("GET", "/temperature2", true);
- xhttp.send();
- }, webDuration ) ;
- setInterval(function () {
- var xhttp = new XMLHttpRequest();
- xhttp.onreadystatechange = function() {
- if (this.readyState == 4 && this.status == 200) {
- document.getElementById("humidity2").innerHTML = this.responseText;
- }
- };
- xhttp.open("GET", "/humidity2", true);
- xhttp.send();
- }, webDuration ) ;
- setInterval(function () {
- var xhttp = new XMLHttpRequest();
- xhttp.onreadystatechange = function() {
- if (this.readyState == 4 && this.status == 200) {
- document.getElementById("date_time").innerHTML = this.responseText;
- }
- };
- xhttp.open("GET", "/date_time", true);
- xhttp.send();
- }, webDuration ) ;
- </script>
- </html>)rawliteral";
- /* end html page conception and scripts ****************************************/
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement