I like expanding my skills by adding to and combining projects. To this great web server temperature/humidity project, I’ve added a 1.8″ TFT screen display, and it works very well!
So far so good. Now, let’s add another feature: a green LED lights up if the WiFi and sensor connections are working, and a red LED lights up if WiFi or sensor connections are NOT working.
It doesn’t seem that easy. Simply wiring in a RGB LED and adding digitalWrite in the proper else/if statements makes the TFT screen go blank (but the web server operates just fine) and the LEDs don’t really operate as expected.
The printToTFT() function at the end worked fine before introducing all the LED stuff … I made it a function because I’m a noob, trying things out.
//Random Nerd Tutorials Online // ESP32 Temp/HumidityWebServer https://randomnerdtutorials.com/esp32-dht11-dht22-temperature-humidity-web-server-arduino-ide/ // // The TFT display portion created by Donnie 10/13/2020 but subject to // future revisions probably regarding presentation // Import required libraries ///////// #include "WiFi.h" #include "ESPAsyncWebServer.h" #include <Adafruit_Sensor.h> #include <DHT.h> #include <Adafruit_ST7735.h> #include <Adafruit_ST7789.h> #include <Adafruit_ST77xx.h> #include <Adafruit_GFX.h> #include <SPI.h> #include <Fonts\FreeSerif9pt7b.h> // Possible colors to use ////////// #define BLACK 0x0000 #define BLUE 0x001F #define RED 0xF800 #define ORANGE 0xe5f442 #define GREEN 0x07E0 #define CYAN 0x07FF #define MAGENTA 0xF81F #define YELLOW 0xFFE0 #define WHITE 0xFFFF #define waitTime 5000 // Adding LED operational feedback //////// #define greenLED 4 // the green leg of a RGB LED #define redLED 19 // the red leg of a RGB LED // the blue leg of the RGB LED isn't connected to anything // Replace with your network credentials///////// const char* ssid = "******"; const char* password = "******"; #define DHTPIN 18 // Digital pin connected to the DHT sensor////// // Uncomment the type of sensor in use: //#define DHTTYPE DHT11 // DHT 11 #define DHTTYPE DHT22 // DHT 22 (AM2302) // Using my DHT22 //#define DHTTYPE DHT21 // DHT 21 (AM2301) //define pins of TFT screen ////////////////////////// #define TFT_CS 15 #define TFT_RST 4 #define TFT_DC 12 #define TFT_SCLK 14 #define TFT_MOSI 13 Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS, TFT_DC, TFT_MOSI, TFT_SCLK, TFT_RST); DHT dht(DHTPIN, DHTTYPE); float t = dht.readTemperature(true); int h = dht.readHumidity(); // Create AsyncWebServer object on port 80 AsyncWebServer server(80); String readDHTTemperature() { // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor) // Read temperature as Fahrenheit (isFahrenheit = true) float t = dht.readTemperature(true); // Check if any reads failed and exit early (to try again). if (isnan(t)) { Serial.println("Failed to read from DHT sensor!"); digitalWrite(redLED,HIGH); // red for not online digitalWrite(greenLED,LOW); return "--"; } else { Serial.println(t); digitalWrite(redLED,LOW); digitalWrite(greenLED,HIGH); // green for is online return String(t); } } String readDHTHumidity() { // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor) int h = dht.readHumidity(); if (isnan(h)) { Serial.println("Failed to read from DHT sensor!"); digitalWrite(redLED,HIGH); digitalWrite(greenLED,LOW); return "--"; } else { Serial.println(h); //okLight(); digitalWrite(redLED,LOW); digitalWrite(greenLED,HIGH); return String(h); } } 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"> <title>Home Office T/H</title> <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 Temp & Humidity</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">°F</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"; // Replaces placeholder with DHT values 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); tft.initR(INITR_BLACKTAB);//initialize a ST7735S chip, black tab dht.begin(); pinMode(redLED, OUTPUT); pinMode(greenLED, OUTPUT); digitalWrite(redLED,LOW); digitalWrite(greenLED,LOW); tft.setFont(&FreeSerif9pt7b); tft.fillScreen(BLACK); delay(waitTime); // Connect to Wi-Fi WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { digitalWrite(redLED,HIGH); digitalWrite(greenLED,LOW); delay(1000); Serial.println("Connecting to WiFi.."); } // Print ESP32 Local IP Address digitalWrite(greenLED,HIGH); digitalWrite(redLED,LOW); Serial.println(WiFi.localIP()); //okLight(); // Route for root / web page 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()); }); // Start server server.begin(); Serial.println(t); Serial.println(h); } void printToTFT() { float t = dht.readTemperature(true); int h = dht.readHumidity(); tft.setRotation(2); tft.setTextWrap(false); tft.fillScreen(BLACK); tft.setCursor(10, 20); tft.setTextColor(RED); tft.setTextSize(1); tft.println("Temp:"); tft.setTextSize(2); tft.setCursor(30, 60); tft.print(t); tft.setTextSize(1); tft.println(" F"); tft.setCursor(10, 100); tft.setTextColor(BLUE); tft.setTextSize(1); tft.println("Humidity"); tft.setTextSize(2); tft.setCursor(45, 139); tft.print(h); tft.setTextSize(1); tft.println("%"); // draw two rectangles. Temp: red, Humid: blue tft.drawRect(0, 0, tft.width(), tft.height() / 2, RED); tft.drawRect(0, 82, tft.width(), tft.height() / 2 - 4, BLUE); delay(waitTime); } void loop() { printToTFT(); }
Also, if it matters, I’m using a common cathode RGB LED
Just from looking at your defines you have both your greenLED and TFT_RST defined as pin 4 so when you try to turn on the green LED your TFT screen will reset which is exactly what you see. You’ll need to find a different pin to use for your green LED.
Well. 90% of the time, the problems come down to something really simple. Yep, that was it. Thanks Brother Steve! The red and green leds light up as expected. You know, earlier, I looked at the TFT display and for a split second it did register the readings, and then blip, out. That would indeed explain the restart pin issue.
I will have another one or two questions regarding code structure, and how I can clean things up. This sketch is a mess, and I’d like to begin using functions more, and also make the web page code its own .h and have it appear on a separate tab. This whole one .ino for everything isn’t elegant. I was a web developer once upon a time, not a terribly good one, as I’ve not done it in a number of years, but having clean code is still a goal.
Don
A couple things I would suggest. First looking into C++ and OOP classes. Once you get it you’ll never go back. Secondly, PlatformIO as your IDE. That will give you a lot to learn but will be fulfilling once you understand both. Hopefully you used PHP classes as a web developer. That will give you a leg up.
One thing I did learn today, is that functions need to be defined in the code before they’re called. They can’t just be added at the end. I kept getting “not defined in this scope” errors, and thought about sticking them near the top. NOW my functions work when called!
I’m no stranger to PHP or Javascript – though it seems lately that Python is the language du juor. With javascript, the DOM and OOP were what I aspired to utilize. I also really liked .NET framework, and C#, using Visual Studio was fun, but I never learned enough to get paid for it. I took a university continuing ed certificate in Flash ActionScript Development, about a year before Flash AS3 went to Valhalla. I’ll put off PlatformIO for a bit. For my birthday next month, I’m asking for a Jetson Nano and bits/pieces to go along with it. There’s always tons to learn. But now, as a hobby, there’s less stress!
Actually, PlatformIO is the easier way to go. I would really recommend you look at it. It’s the IDE of the future and makes things so much easier. I resisted for a long time but I have now been assimilated.
i also went with Flash Actionscript with Adobe Flex. That’s a good intro to OOP so I think you would have a good basis to move forward.
Hi Donald.
If you want to start looking into PlatformIO, you can take a look at our getting started tutorial: https://randomnerdtutorials.com/vs-code-platformio-ide-esp32-esp8266-arduino/
It is much easier to develop your web server using PlatformIO + VSCode. You can have several tabs opened and it is easy to have separated HTML, CSS and JavaScript files to create the web page.
Additionally, it comes with tools that allow you to upload those files to your board filesystem without having to install additional plugins.
Something that is really useful is that it detects errors before you upload the code, so it saves you a ton of time.
We’re currently creating new content about how to use PlatformIO + VSCode to create your web servers in a more organized way. It should be out in a month or so.
Regards,
Sara