DHT22 Test Program for TTGO T-Display Part 2

 
//////////////////////////////////////////////////////////////////
// DHT22 Test program for the ESP32 TTGO-T Display              //
// Jordan Rubin 2020                                            //
// More at https://www.youtube.com/c/jordanrubin6502            //
// http://technocoma.blogspot.com                               //
//////////////////////////////////////////////////////////////////
// Provides a graphical output on the built in display of the TTGO for both
// Temperature and humidity or switch between those and heat index with a
// push of a button.  The second button switches everything between Celsius
// and Fahrenheit. Both switches have built in interupt and debounce. View
// values from device remotely at http://esp32dht.local
// Directly related to the video https://youtu.be/CeFf6K9R2Ig

const char MAIN_webpage[] PROGMEM = R"=====(
<!DOCTYPE html>
<html>
  <head>
    <title>ESP32 DHT22 IOT Beginner Project</title>
    <meta content="text/html;charset=utf-8" http-equiv="Content-Type">
    <meta content="utf-8" http-equiv="encoding">
  </head>
  <style>
table {
  border-spacing: 1;
  border-collapse: collapse;
  background: white;
  border-radius: 6px;
  overflow: hidden;
  max-width: 800px;
  width: 100%;
  margin: 0 auto;
  position: relative;
}
table * {
  position: relative;
}
table td, table th {
  padding-left: 8px;
}
table thead tr {
  height: 60px;
  background: #95C1F7;
  font-size: 16px;
}
table tbody tr {
  height: 48px;
  border-bottom: 1px solid #E3F1D5;
}
table tbody tr:last-child {
  border: 0;
}
table td, table th {
  text-align: left;
}
table td.l, table th.l {
  text-align: right;
}
table td.c, table th.c {
  text-align: center;
}
table td.r, table th.r {
  text-align: center;
}

@media screen and (max-width: 35.5em) {
  table {
    display: block;
  }
  table > *, table tr, table td, table th {
    display: block;
  }
  table thead {
    display: none;
  }
  table tbody tr {
    height: auto;
    padding: 8px 0;
  }
  table tbody tr td {
    padding-left: 45%;
    margin-bottom: 12px;
  }
  table tbody tr td:last-child {
    margin-bottom: 0;
  }
  table tbody tr td:before {
    position: absolute;
    font-weight: 700;
    width: 40%;
    left: 10px;
    top: 0;
  }
  table tbody tr td:nth-child(1):before {
    content: "Code";
  }
  table tbody tr td:nth-child(2):before {
    content: "Stock";
  }
  table tbody tr td:nth-child(3):before {
    content: "Cap";
  }
  table tbody tr td:nth-child(4):before {
    content: "Inch";
  }
  table tbody tr td:nth-child(5):before {
    content: "Box Type";
  }
}
body {
  background: #AAB6C4;
  font: 400 14px 'Calibri','Arial';
  padding: 20px;
}

blockquote {
  color: white;
  text-align: center;
}
  </style>  
  <body>
  <table>
      <thead>
        <tr>
          <th>DHT22 Temp Sensor</th>
          <th>
            <input type="radio" id="mvalC" name="measurement" value="C"checked>
            <label for="C">Celsius</label><br>
            <input type="radio" id="mvalF" name="measurement" value="F">
            <label for="F">Fahrenheit</label><br>
          </th>
        </tr>
      <thead>
      <tbody>
        <tr>
          <td>Temperature</td>
          <td><span id="tempVal"></span></td>
        </tr>
           <tr>
          <td>Humidity</td>
          <td><span id="humVal"></span</td>
        </tr>
           <tr>
          <td>Heat Index</td>
          <td><span id="hidxVal"></span></td>
        </tr>
      </tbody>
    <table/>   
    <blockquote> <a href="http:\/\/www.youtube.com/c/jordanrubin6502" target="_blank"> Retro Tech & Electronics Channel</a> </blockquote>    
      <script>
        setInterval(function() {getData();}, 2000); //2 Second update

///////////////////////////////// getData() field refresher
function getData() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      var myArr = JSON.parse(this.responseText);
      var measure = document.querySelector('input[name=measurement]:checked').value;  //F|C
      var temp = myArr.temp;
      var hIndex = myArr.heatIndex;
      var isFahrenheit = myArr.isFahrenheit;
       if (isFahrenheit == 1){
        if (measure == 'C'){
            temp   = (temp - 32) * 0.55555;
            temp = temp.toFixed(2);
            hIndex = (hIndex - 32) * 0.55555;
            hIndex = hIndex.toFixed(2);
          }
       }
      else {
        if (measure == 'F'){
            temp = temp * 1.8 + 32;
            temp = temp.toFixed(2);
            hIndex = hIndex * 1.8 + 32;
            hIndex = hIndex.toFixed(2);
         }
      }
      document.getElementById("tempVal").innerHTML = temp+measure;
      document.getElementById("humVal").innerHTML = myArr.humidity+'%';
      document.getElementById("hidxVal").innerHTML = hIndex+measure;
    }
  };
  xhttp.open("GET", "readDATA", true);
  xhttp.send();
}
///////////////////////////////////////////////////////////////////
    </script>      
  </body>
</html>
)=====";

#include <DHT.h>
#include <TFT_eSPI.h>
#include <WiFi.h>
#include <AsyncTCP.h>
#include <ESPAsyncWebServer.h>
#include <ESPmDNS.h>

#define DHTPIN 17
#define DHTTYPE DHT22
#define BUTTON1PIN 35
#define BUTTON2PIN 0

DHT dht(DHTPIN, DHTTYPE);
TFT_eSPI tft = TFT_eSPI();
WiFiClient espclient;
AsyncWebServer server(80);
TaskHandle_t Task1;

float   temp;
float   heatIdx;
float   humidity;
bool    asFahrenheit;
bool    useFahrenheit       = true; // Default to Fahrenheit
bool    showTemp            = true; // Default to Temp / Humidity
long    lastDebounceButton1 = 0;    // Holds Button1 last debounce
long    lastDebounceButton2 = 0;    // Holds Button2 last debounce
long    debounceDelay       = 200;  // 200ms between re-polling
const char* ssid            = "myssid";
const char* password        = "mypassw0rd";
const char* deviceName      = "esp32dht";

//////////////////////////////////////////////////////////////////////////
//-FUNCTION-[handleRoot]-------------------------------------------------]
//////////////////////////////////////////////////////////////////////////
void handleRoot(AsyncWebServerRequest *request) {
  String s = MAIN_webpage;
  request->send(200, "text/html", s);
}
//-----------------------------------------------------------------------]


//////////////////////////////////////////////////////////////////////////
//-FUNCTION-[handleDATA]-------------------------------------------------]
//////////////////////////////////////////////////////////////////////////
void handleDATA(AsyncWebServerRequest *request) {
  String tempStr = String(temp);
  String JSONstr = "{\"temp\":\""+tempStr+"\",\"humidity\":\""+humidity+"\",\"heatIndex\":\""+heatIdx+"\",\"isFahrenheit\":\""+asFahrenheit+"\"}";  
 request->send(200, "text/plain", JSONstr);
}
//-----------------------------------------------------------------------]


//////////////////////////////////////////////////////////////////////////
//-FUNCTION-[toggleButton1]----------------------------------------------]
//////////////////////////////////////////////////////////////////////////
void toggleButton1() {  
  if ((millis() - lastDebounceButton1) > debounceDelay) {  
    Serial.print("1-");Serial.println(useFahrenheit);
    if (useFahrenheit){useFahrenheit = false;}
    else {useFahrenheit = true;}
    lastDebounceButton1 = millis();
  }
}
//-----------------------------------------------------------------------]


//////////////////////////////////////////////////////////////////////////
//-FUNCTION-[toggleButton2]----------------------------------------------]
//////////////////////////////////////////////////////////////////////////
void toggleButton2() {
  if ((millis() - lastDebounceButton2) > debounceDelay) {  
    Serial.print("2-");Serial.println(showTemp);
    if (showTemp){showTemp = false;}
    else {showTemp = true;}
    lastDebounceButton2 = millis();
  }
}
//-----------------------------------------------------------------------]


//////////////////////////////////////////////////////////////////////////
//-FUNCTION-[showScrn1]--------------------------------------------------]
//////////////////////////////////////////////////////////////////////////
// What to display if showTemp = true
void showScrn1() {
  float t = dht.readTemperature(useFahrenheit);
  float h = dht.readHumidity();
  if (isnan(h) || isnan(t)) {
    Serial.println(F("Failed to read from DHT sensor!"));
    return;
  }
  temp =t; humidity=h;
  heatIdx = dht.computeHeatIndex(temp, humidity, useFahrenheit);
  asFahrenheit = useFahrenheit;
  tft.fillScreen(TFT_BLACK);
  tft.setTextColor(TFT_GREEN, TFT_BLACK);
  tft.setCursor(0, 30);
  tft.setFreeFont(&Orbitron_Light_24);
  tft.println("Temp     Humidity");
  tft.drawLine(0, 35, 250, 35, TFT_BLUE);
  tft.setCursor(0, 60);
  tft.print(temp);
  if (useFahrenheit){tft.print(F("f"));}
  else {tft.print(F("c"));}
  tft.setCursor(130, 60);
  tft.print(humidity);tft.print(F("%"));
}
//-----------------------------------------------------------------------]


//////////////////////////////////////////////////////////////////////////
//-FUNCTION-[showScrn2]--------------------------------------------------]
//////////////////////////////////////////////////////////////////////////
// What to display if showTemp = false
void showScrn2() {  
  float t = dht.readTemperature(useFahrenheit);
  float h = dht.readHumidity();
  if (isnan(h) || isnan(t)) {
    Serial.println(F("Failed to read from DHT sensor!"));
    return;
  }
  temp =t; humidity=h;
  heatIdx = dht.computeHeatIndex(temp, humidity, useFahrenheit);
  asFahrenheit = useFahrenheit;
  tft.fillScreen(TFT_BLACK);
  tft.setTextColor(TFT_RED, TFT_BLACK);
  tft.setCursor(50, 30);
  tft.setFreeFont(&Orbitron_Light_24);
  tft.println("Heat Index");
  tft.drawLine(0, 35, 250, 35, TFT_BLUE);
  tft.setFreeFont(&Orbitron_Light_32);
  tft.setTextColor(TFT_GREEN, TFT_BLACK);
  tft.setCursor(60, 100);
  tft.print(heatIdx);
  if (useFahrenheit){tft.print(F("f"));}
  else {tft.print(F("c"));}
}
//-----------------------------------------------------------------------]


//////////////////////////////////////////////////////////////////////////
//-FUNCTION-[showSrcnNetwork]--------------------------------------------]
//////////////////////////////////////////////////////////////////////////
// Startup screen with network info
void showSrcnNetwork(){
  tft.fillScreen(TFT_BLACK);
  tft.setTextColor(TFT_ORANGE, TFT_BLACK);
  tft.setCursor(0, 30);
  tft.setFreeFont(&Orbitron_Light_24);
  tft.println("IP");
  tft.setTextColor(TFT_GREEN, TFT_BLACK);
  tft.println(WiFi.localIP());
  tft.setCursor(0, 90);
  tft.setFreeFont(&FreeSerifBold12pt7b);
  tft.setTextColor(TFT_RED, TFT_BLACK);
  tft.print("http://");
  tft.print(deviceName);
  tft.println(".local");
  delay(5000);
}
//-----------------------------------------------------------------------]


//////////////////////////////////////////////////////////////////////////
//-SYSTEM-[setup]--------------------------------------------------------]
//////////////////////////////////////////////////////////////////////////
void setup() {
  Serial.begin(115200);
  WiFi.mode(WIFI_STA);  // Setup the WiFi radio to connect to a wireless access point
  WiFi.begin(ssid, password);
  int i =0;
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
    i++;
    if (i==15){
      Serial.print("\nWifi Conn. Failed, Restarting\n");
      delay(100);
      ESP.restart();
      i=0;
    }
  }
  if (!MDNS.begin(deviceName)){
    Serial.print("Error starting mDNS");
  }
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
  tft.begin();
  tft.setRotation(1); //Landscape
  showSrcnNetwork();
  server.on("/", handleRoot);
  server.on("/readDATA", handleDATA);
  server.begin();
  pinMode(BUTTON1PIN, INPUT);
  pinMode(BUTTON2PIN, INPUT);
  dht.begin();
  xTaskCreatePinnedToCore(Task1code,"Task1", 10000, NULL, 2, &Task1, 0);
}
//-----------------------------------------------------------------------]


//////////////////////////////////////////////////////////////////////////
//-SYSTEM-[Task1code]----------------------------------------------------]
//////////////////////////////////////////////////////////////////////////
void Task1code( void * pvParameters ){
  Serial.print("Task1 running on core ");
  Serial.println(xPortGetCoreID());
  int button1State = 0;
  int button2State = 0;
    for(;;){
      button1State = digitalRead(BUTTON1PIN);
      button2State = digitalRead(BUTTON2PIN);
      if (button1State == LOW) {
        toggleButton1();
      }
      if (button2State == LOW) {
        toggleButton2();
      }
      delay(10);
    }
}
//-----------------------------------------------------------------------]


//////////////////////////////////////////////////////////////////////////
//-SYSTEM-[loop]---------------------------------------------------------]
//////////////////////////////////////////////////////////////////////////
void loop() {
      delay(2000);  //Required by this device to function properly
      if (showTemp){showScrn1();} // Temp Humidity
      else {showScrn2();}         // Heat Index
}
//-----------------------------------------------------------------------]

No comments:

Post a Comment