Complete ESP32 IoT Temperature and Humidity Monitor for Beginners
by sarful in Circuits > Arduino
83 Views, 0 Favorites, 0 Comments
Complete ESP32 IoT Temperature and Humidity Monitor for Beginners
Objective
The project measures temperature and humidity using a DHT11 sensor connected to an ESP32. The ESP32 sends this data to a web page, logs it to Google Sheets, sends alerts if thresholds are exceeded, and controls a fan or heater.
System Overview
- DHT11 Sensor: Reads temperature and humidity.
- ESP32 Web Server: Displays real-time data in a web browser.
- Google Sheets Logging: Records data every minute.
- Alert System: Sends alerts based on specific conditions.
- Relay Control: Turns on a fan or heater if the temperature exceeds a set threshold.
Supplies
Required Components with Amazon Links
- ESP32: Buy on Amazon
- DHT11 Sensor: Buy on Amazon
- Jumper Wires: Buy on Amazon
- Relay Module: Buy on Amazon
- OLED Display (SSD1306): Buy on Amazon
Affiliate Link Disclaimer: These links are affiliate links, meaning purchases made through them help support free tutorials at no additional cost.
Circuit Connection
- DHT11 Sensor:
- Data Pin connects to GPIO4 on ESP32.
- VCC connects to 3.3V on ESP32.
- GND connects to GND on ESP32.
- Relay Module (to control fan or heater):
- IN1 connects to GPIO13 on ESP32.
- VCC connects to 3.3V on ESP32.
- GND connects to GND on ESP32.
- OLED Display (Optional):
- SDA connects to GPIO21 on ESP32.
- SCL connects to GPIO22 on ESP32.
- GND connects to GND on ESP32.
- VCC connects to 3.3V on ESP32.
Step-by-Step Guide
Step 1: Set Up the ESP32 in Arduino IDE
- Install ESP32 Board Support:
- Open Arduino IDE, go to File > Preferences.
- In the "Additional Boards Manager URLs" field, add this URL:
https://dl.espressif.com/dl/package_esp32_index.json
- Go to Tools > Board > Boards Manager, search for "ESP32", and click Install.
- Install Required Libraries:
- Go to Sketch > Include Library > Manage Libraries....
- Search for and install these libraries:
- DHT sensor library (for the DHT11 sensor).
- Adafruit SSD1306 and Adafruit GFX (for the OLED display, if using).
- WiFi (for ESP32 WiFi functions).
- HTTPClient (for logging to Google Sheets).
Step 2: Set Up Google Sheets for Data Logging
- Create a New Google Sheet:
- Name it something like "ESP32 Temperature Data."
- Make sure it’s accessible.
- Set Up Google Apps Script:
- Go to Extensions > Apps Script in your Google Sheet.
- Delete any existing code and paste the following:
function doGet(e) {
var sheet = SpreadsheetApp.openById("YOUR_SHEET_ID").getActiveSheet();
var row = [new Date(), e.parameter.temperature, e.parameter.humidity];
sheet.appendRow(row);
return ContentService.createTextOutput("Success");
}
- Replace "YOUR_SHEET_ID" with the actual ID of your Google Sheet (found in the URL after /d/ and before /edit).
- Click Deploy > Test Deploy as Web App.
- Select Execute as: Me, and choose Anyone, even anonymous under "Who has access."
- Click Deploy and copy the Web App URL. You’ll need it in the Arduino code.
Step 3: Understanding the Arduino Code
The code below does the following:
- Connects the ESP32 to WiFi.
- Reads temperature and humidity from the DHT11 sensor.
- Displays data on a web page.
- Logs data to Google Sheets.
- Controls a relay based on the temperature threshold.
- Displays data on an OLED screen (optional).
Arduino Code:
#include <WiFi.h>
#include <Wire.h>
#include "DHT.h"
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <HTTPClient.h>
#define DHTPIN 4 // DHT11 Data Pin
#define RELAY_PIN 13 // Relay Pin
#define OLED_RESET -1 // OLED Reset (Not used)
#define DHTTYPE DHT11 // DHT11 sensor type
DHT dht(DHTPIN, DHTTYPE); // Initialize DHT
Adafruit_SSD1306 display(128, 64, &Wire, OLED_RESET);
const char* ssid = "YourWiFiSSID"; // Your WiFi SSID
const char* password = "YourWiFiPassword"; // Your WiFi Password
const char* googleSheetURL = "YOUR_GOOGLE_SHEET_WEB_APP_URL"; // Google Sheets URL
WiFiServer server(80); // Start Web Server on port 80
float temperature; // Store temperature
float humidity; // Store humidity
void setup() {
Serial.begin(115200);
dht.begin(); // Start DHT sensor
pinMode(RELAY_PIN, OUTPUT); // Set Relay pin as output
digitalWrite(RELAY_PIN, LOW); // Start relay off
display.begin(SSD1306_SWITCHCAPVCC, 0x3C); // Initialize OLED display
display.clearDisplay();
// Connect to WiFi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("\nConnected to WiFi");
Serial.print("ESP32 IP Address: ");
Serial.println(WiFi.localIP());
server.begin(); // Start the server
}
void loop() {
// Read data from DHT11 sensor
temperature = dht.readTemperature();
humidity = dht.readHumidity();
if (isnan(temperature) || isnan(humidity)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
// Display data on OLED (optional)
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(WHITE);
display.setCursor(0, 0);
display.print("Temp: ");
display.print(temperature);
display.print(" C");
display.setCursor(0, 16);
display.print("Humidity: ");
display.print(humidity);
display.print(" %");
display.display();
// Relay control based on temperature threshold
if (temperature > 30) { // Adjust threshold as needed
digitalWrite(RELAY_PIN, HIGH); // Turn relay on
} else {
digitalWrite(RELAY_PIN, LOW); // Turn relay off
}
// Log data to Google Sheets
HTTPClient http;
String url = googleSheetURL + "?temperature=" + String(temperature) + "&humidity=" + String(humidity);
http.begin(url.c_str());
int httpResponseCode = http.GET();
if (httpResponseCode > 0) {
Serial.println("Data logged to Google Sheets");
} else {
Serial.println("Error logging data");
}
http.end();
// Web server code to display data on a webpage
WiFiClient client = server.available();
if (client) {
Serial.println("Client connected");
String request = client.readStringUntil('\r');
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println("Connection: close");
client.println();
String htmlPage = "<!DOCTYPE HTML><html><head><title>ESP32 IoT Monitor</title>";
htmlPage += "<meta http-equiv='refresh' content='10'><style>body { font-family: Arial; text-align: center; color: #333; background-color: #f0f0f5; margin-top: 50px; }";
htmlPage += "h1 { font-size: 2em; color: #555; } .data { font-size: 1.5em; color: #007BFF; padding: 20px; }</style></head><body>";
htmlPage += "<h1>ESP32 Temperature and Humidity Monitor</h1>";
htmlPage += "<div class='data'>Humidity: " + String(humidity) + " %</div>";
htmlPage += "<div class='data'>Temperature: " + String(temperature) + " °C</div>";
htmlPage += "</body></html>";
client.print(htmlPage);
delay(10);
client.stop();
}
delay(60000); // Log data every 60 seconds
}
Step 4: Upload Code to ESP32
- Connect ESP32 to your computer via USB.
- Select ESP32 Dev Module in Arduino IDE under Tools > Board.
- Choose the correct port under Tools > Port.
- Click Upload to transfer the code to ESP32.
Running the Project
- Open Serial Monitor in Arduino IDE to check for WiFi connection and obtain the ESP32’s IP address.
- In a web browser connected to the same WiFi network, type the IP address to view the data.
- Monitor the OLED display for temperature and humidity readings.
- Observe relay control based on the temperature threshold.
Check Output
- OLED Display: Displays the current temperature and humidity.
- Web Interface: Displays data, refreshing every 10 seconds.
- Google Sheets: Logs data every minute.
- Relay: Turns on/off based on the temperature threshold.
FAQ
- How to change WiFi credentials?
- Update ssid and password variables in the code.
- What if the OLED screen is blank?
- Ensure connections are correct, and confirm the display address (0x3C).
- What if the relay doesn’t work?
- Check the threshold code and wiring to the relay module.
Recommended Book
Arduino Programming for Absolute Beginners
An ideal book for those new to Arduino, this guide covers programming basics with real projects.
For more free tutorials on Arduino, ESP8266, ESP32, and Raspberry Pi, visit: MechatronicsLab.net