ESP32 Weather Data Logger With DHT Sensor (ThingSpeak + Google Sheets)

by sarful in Circuits > Arduino

42 Views, 2 Favorites, 0 Comments

ESP32 Weather Data Logger With DHT Sensor (ThingSpeak + Google Sheets)

1 DHT22 - Digital Temperature and Humidity Sensors.png

In this project, you will create an ESP32-based weather data logger that reads temperature and humidity from a DHT22 sensor (connected to Pin D4). The data is uploaded to ThingSpeak for real-time visualization and logged into Google Sheets for storage and further analysis. This project is perfect for monitoring weather conditions over time and analyzing the data using Google Sheets' built-in capabilities.

Supplies

Components Required:

  1. ESP32 – Microcontroller with Wi-Fi capabilities.
  2. DHT22 Sensor – Temperature and humidity sensor.
  3. Jumper Wires – For connecting components.
  4. Breadboard – For prototyping.
  5. 4.7kΩ Resistor – Pull-up resistor for the DHT22 data pin.
  6. Power Supply – To power the ESP32.
  7. ThingSpeak Account – Platform to visualize the data.
  8. Google Sheets Account – For storing the data.


Wiring the Components:

  1. DHT22 to ESP32:
  2. VCC of DHT22 → 3.3V on ESP32.
  3. GND of DHT22 → GND on ESP32.
  4. Data Pin of DHT22 → Pin D4 on ESP32.
  5. 4.7kΩ Resistor between VCC and Data Pin of the DHT22.

Setting Up ThingSpeak for Data Upload

Step 1: Create a ThingSpeak Account

  1. Sign up at ThingSpeak:
  2. Go to ThingSpeak and sign up for a free account if you don't already have one. It will require basic details such as your name, email, and password.
  3. Create a New Channel:
  4. After logging in, click on the Channels tab in the navigation bar.
  5. Click on + New Channel to create a new channel for storing your weather data.
  6. Configure Channel Fields:
  7. Field 1: Name it "Temperature (°C)" for storing the temperature data.
  8. Field 2: Name it "Humidity (%)" for storing the humidity data.
  9. You can leave the other options as default for now.
  10. Save your channel.
  11. Get the Channel ID and Write API Key:
  12. After saving the channel, ThingSpeak will provide you with a Channel ID and a Write API Key.
  13. Note these down. You’ll need these to upload data to your ThingSpeak channel.
  14. Set Up Visualization (Optional):
  15. Once your channel is created, you can create a Dashboard in ThingSpeak to visualize the data. This will allow you to monitor the temperature and humidity in real-time.
  16. You can go to the Visualization tab and create widgets like Gauge for temperature and humidity.

Setting Up Google Sheets for Data Logging

Step 1: Create a Google Sheet

  1. Open Google Sheets by going to Google Sheets.
  2. Create a new spreadsheet:
  3. Name the sheet "Weather Data Logger" or something similar to indicate it will be used for logging weather data.
  4. In the first row, create the following column headers:
  5. Column A: Timestamp – For storing the time at which the data was logged.
  6. Column B: Temperature (°C) – For storing the temperature readings from the DHT22 sensor.
  7. Column C: Humidity (%) – For storing the humidity readings from the DHT22 sensor.
  8. This spreadsheet will now be the destination for your weather data.

Step 2: Create a Google Apps Script for Data Logging

To automatically pull data from ThingSpeak and insert it into your Google Sheets, we need to create a Google Apps Script.

  1. Open Apps Script:
  2. Go to Extensions → Apps Script in your Google Sheets document.
  3. This will open the script editor where you can write a custom script to fetch data from ThingSpeak.
  4. Write the Apps Script Code:
  5. Delete any default code and replace it with the following script:
function logWeatherData() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var url = "https://api.thingspeak.com/channels/YOUR_CHANNEL_ID/feeds/last.json?api_key=YOUR_API_KEY";
// Fetch the last data point from ThingSpeak
var response = UrlFetchApp.fetch(url);
var json = JSON.parse(response.getContentText());
// Extract timestamp, temperature, and humidity from the JSON response
var timestamp = json.created_at;
var temperature = json.field1; // Field 1 is temperature
var humidity = json.field2; // Field 2 is humidity
// Append the data to the sheet
sheet.appendRow([timestamp, temperature, humidity]);
}
  1. Replace the placeholders:
  2. Replace YOUR_CHANNEL_ID with your ThingSpeak Channel ID.
  3. Replace YOUR_API_KEY with your ThingSpeak Write API Key.
  4. Save the Script:
  5. After writing the script, click File → Save and name your script (e.g., "ThingSpeakLogger").

Step 3: Set Up Triggers to Run the Script Automatically

  1. Click on the Clock icon in the toolbar, or go to Triggers from the Apps Script editor.
  2. Click + Add Trigger at the bottom right.
  3. Select the following options:
  4. Choose function: logWeatherData
  5. Choose deployment: Head
  6. Event source: Time-driven
  7. Type of time-based trigger: Set this to run every 10 minutes (or any other interval you prefer).
  8. Click Save.

This setup will now automatically fetch the latest weather data from ThingSpeak and log it into Google Sheets at the interval you set.

Complete Arduino Code

Here is the complete Arduino code that connects the ESP32 to Wi-Fi, reads data from the DHT22 sensor, uploads the data to ThingSpeak, and logs it into Google Sheets via Apps Script.

#include <WiFi.h>
#include <DHT.h>
#include <ThingSpeak.h>

// Wi-Fi credentials
const char* ssid = "your-SSID"; // Replace with your Wi-Fi SSID
const char* password = "your-password"; // Replace with your Wi-Fi password

// ThingSpeak credentials
#define THINGSPEAK_API_KEY "your-Write-API-Key" // Replace with your ThingSpeak API key
#define THINGSPEAK_CHANNEL_ID "your-Channel-ID" // Replace with your ThingSpeak Channel ID

// DHT22 sensor setup
#define DHTPIN 4 // DHT22 data pin connected to GPIO 4 (D4)
#define DHTTYPE DHT22 // Define DHT sensor type as DHT22

DHT dht(DHTPIN, DHTTYPE); // Initialize DHT sensor
WiFiClient client;

void setup() {
// Start Serial Monitor
Serial.begin(115200);

// Connect to Wi-Fi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to Wi-Fi");

// Initialize ThingSpeak
ThingSpeak.begin(client);

// Initialize DHT sensor
dht.begin();
}

void loop() {
// Read temperature and humidity from DHT22 sensor
float temperature = dht.readTemperature(); // Temperature in Celsius
float humidity = dht.readHumidity(); // Humidity in percentage

// Check if the readings are valid
if (isnan(temperature) || isnan(humidity)) {
Serial.println("Failed to read from DHT sensor!");
return;
}

// Print the values to Serial Monitor
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.print(" °C ");
Serial.print("Humidity: ");
Serial.print(humidity);
Serial.println(" %");

// Upload data to ThingSpeak
ThingSpeak.setField(1, temperature); // Set Field 1 as temperature
ThingSpeak.setField(2, humidity); // Set Field 2 as humidity
// Write to ThingSpeak every 15 seconds
int responseCode = ThingSpeak.writeFields(THINGSPEAK_CHANNEL_ID, THINGSPEAK_API_KEY);
if (responseCode == 200) {
Serial.println("Data sent to ThingSpeak successfully");
} else {
Serial.println("Error sending data to ThingSpeak");
}

// Wait for 15 seconds before sending new data
delay(15000); // 15 seconds delay before the next upload
}

Steps to Test the Project:

  1. Upload the Code:
  2. Connect the ESP32 to your computer via USB.
  3. Open Arduino IDE, select the correct board and port under the Tools menu.
  4. Upload the code to the ESP32.
  5. Monitor the Serial Output:
  6. Open the Serial Monitor in Arduino IDE (set the baud rate to 115200) to see the status of the Wi-Fi connection, temperature, and humidity readings.
  7. Check ThingSpeak:
  8. Go to your ThingSpeak Channel to monitor the uploaded data. You should see temperature and humidity values being updated every 15 seconds.
  9. Check Google Sheets:
  10. Open your Google Sheets document. The data should start populating with the timestamp, temperature, and humidity values logged at regular intervals as per the trigger you set up.

Conclusion:

This project successfully sets up an ESP32 Weather Data Logger with a DHT22 sensor. The data is uploaded to ThingSpeak for real-time monitoring and visualization, while also being logged into Google Sheets for storage and analysis. This system can be used for various applications, such as home automation, environmental monitoring, and data analysis.

Affiliate Disclaimer:

Some of the links in this article are affiliate links, which means I may earn a small commission if you make a purchase through them, at no extra cost to you. Thank you for supporting my work!