🍇 Raspberry Pi IoT Project

DHT11 + Raspberry Pi + ThingSpeak + GitHub Pages

A fully standalone IoT project — sensor reads temperature & humidity, Raspberry Pi sends data to the cloud, and a live dashboard on GitHub Pages lets you monitor from anywhere in the world.

Sensor → Raspberry Pi → ThingSpeak → GitHub Pages → Any Device

📋 Project Overview

This is a fully standalone IoT project where:

🔄 Complete Data Flow

🌡️ DHT11 Sensor
🍇 Raspberry Pi
(Python Script)
☁️ ThingSpeak
(Write API Key)
🌐 GitHub Pages
(Read API Key)
📱 Any Device
(Phone/PC/Tablet)

🧠 Technology Stack (Keep This in Mind)

🔧 Hardware Raspberry Pi + DHT11
🐍 Backend (Device Side) Python
☁️ Cloud ThingSpeak
🌐 Frontend Hosting GitHub Pages
📡 Protocol HTTP + REST API
1

🔌 Hardware Connection (VERY IMPORTANT)

1️⃣ DHT11 Pin Details

DHT11 PinMeaning
VCCPower (3.3V or 5V)
DATAData output
GNDGround
👍 Tip: If you're using a DHT11 module (the one on a small PCB), the pull-up resistor is already present — no need to add one externally.

2️⃣ Raspberry Pi Pins to Use

DHT11 PinRaspberry Pi PinPhysical Pin #
VCC3.3VPin 1
DATAGPIO4Pin 7
GNDGNDPin 6
📌 We use GPIO4 because it's stable and commonly supported by sensor libraries.

🔌 Wiring Diagram

Raspberry Pi DHT11 Module ┌──────────────────┐ ┌─────────┐ │ │ │ │ │ Pin 1 (3.3V) ──┼──────────────┤ VCC │ │ │ │ │ │ Pin 7 (GPIO4) ─┼──────────────┤ DATA │ │ │ │ │ │ Pin 6 (GND) ───┼──────────────┤ GND │ │ │ │ │ └──────────────────┘ └─────────┘ 📌 If bare DHT11 (4-pin): Add 10kΩ pull-up between VCC and DATA 📌 If DHT11 module (3-pin): No resistor needed

🔧 Components Required

Raspberry Pi (any model with GPIO) DHT11 Sensor / Module Jumper Wires (Female-to-Female) Breadboard (optional) MicroSD Card (with Raspberry Pi OS) Power Supply (5V/3A for Pi) WiFi Connection
2

💻 Prepare Raspberry Pi (Software Setup)

Open the terminal on your Raspberry Pi and run these commands:

Update System Packages

Terminal
sudo apt update
sudo apt install python3-pip -y

Install Required Python Libraries

Terminal
pip3 install adafruit-circuitpython-dht requests
sudo apt install libgpiod2 -y

What Each Package Does

PackagePurpose
adafruit-circuitpython-dhtLibrary to read DHT11/DHT22 sensor data
requestsPython library to make HTTP requests (send data to ThingSpeak)
libgpiod2Low-level GPIO library required by Adafruit DHT library
Now Pi is ready to read the sensor and send data online.
3

📁 Create Project Folder & File Structure

Folder Structure

iot-project/ │── send_to_thingspeak.py ← Python file (device side) │── README.md ← (optional documentation)

Create the Folder

Terminal
mkdir iot-project
cd iot-project
4

☁️ Create ThingSpeak Account (DO THIS FIRST)

📌 ThingSpeak is your cloud database. It stores sensor data and provides API access for reading/writing.

Steps to Set Up ThingSpeak

Go to ThingSpeak

Visit 👉 https://thingspeak.com

Sign Up / Log In

Create a free account (you can use your MathWorks account)

Create a New Channel

Click "New Channel" button

Configure Fields

Fill in the channel details:

FieldName
Field 1Temperature
Field 2Humidity
Save the Channel

Click Save Channel

Get Your API Keys

Go to the API Keys tab. You will get:

API Keys You Need

KeyPurposeExample
Channel IDUnique identifier for your channel3272751
Write API KeyUsed by Raspberry Pi to SEND dataABC123XYZ...
Read API KeyUsed by website to FETCH dataDEF456UVW...
⚠️ Keep your Write API Key secret! Only the Read API Key should be used in public-facing code (HTML).
5

🐍 Create Python File (Send Data to Cloud)

Create the File

Terminal
nano send_to_thingspeak.py

✅ FINAL Python Code

Python — send_to_thingspeak.py
import time
import requests
import board
import adafruit_dht

# ─── Configuration ───
WRITE_API_KEY = "YOUR_WRITE_API_KEY"
THINGSPEAK_URL = "https://api.thingspeak.com/update"

# ─── Initialize DHT11 on GPIO4 ───
dht = adafruit_dht.DHT11(board.D4)  # GPIO4

while True:
    try:
        temperature = dht.temperature
        humidity = dht.humidity

        if temperature is not None and humidity is not None:
            payload = {
                "api_key": WRITE_API_KEY,
                "field1": temperature,
                "field2": humidity
            }

            requests.post(THINGSPEAK_URL, data=payload)
            print(f"Sent → Temp: {temperature}°C  Humidity: {humidity}%")

    except Exception as e:
        print("Sensor error:", e)

    time.sleep(15)  # ThingSpeak minimum interval

Code Explanation

Line / BlockWhat It Does
import adafruit_dhtImports the DHT sensor library
board.D4Refers to GPIO4 on Raspberry Pi
dht.temperatureReads the current temperature in °C
dht.humidityReads the current humidity in %
requests.post(...)Sends data to ThingSpeak via HTTP POST
payloadDictionary with API key + field values
time.sleep(15)Waits 15 seconds (ThingSpeak free tier minimum)
try/exceptCatches sensor read errors (common with DHT11)

Save & Exit

In nano editor:
Save → Ctrl + O then press Enter
Exit → Ctrl + X
6

▶️ Run Python Script

Execute the Script

Terminal
python3 send_to_thingspeak.py

Expected Output

Output
Sent → Temp: 28°C  Humidity: 64%
Sent → Temp: 28°C  Humidity: 63%
Sent → Temp: 29°C  Humidity: 62%
... (every 15 seconds)

Verify on ThingSpeak

Go to your ThingSpeak Channel
Check the charts — you should see data points appearing
Entries count will increase 📈 with each reading
👉 Now refresh ThingSpeak → Entries will increase 📈
This confirms hardware + cloud is working!
⚠️ If you see "Sensor error" — this is normal occasionally. DHT11 sometimes fails to read. The try/except block handles this gracefully. The script continues running.
7

🌐 Create HTML Dashboard (Frontend)

Now we build the viewer side. This HTML page fetches data from ThingSpeak using the Read API Key and displays it live.

1️⃣ Create GitHub Repository

Go to GitHubgithub.com/new
Repository Name: iot-dashboard
Set to Public
Click Create Repository

2️⃣ Create index.html

Create a new file called index.html in the repository and paste this code:

HTML — index.html
<!DOCTYPE html>
<html>
<head>
  <title>IoT Temperature Monitoring</title>
  <style>
    body { font-family: Arial; text-align: center; }
    .card {
      display: inline-block;
      padding: 20px;
      margin: 15px;
      border-radius: 10px;
      box-shadow: 0 0 10px #aaa;
      width: 220px;
    }
  </style>
</head>
<body>

<h1>🌍 IoT Temperature & Humidity Dashboard</h1>

<div class="card">
  <h2>🌡 Temperature</h2>
  <p id="temp">-- °C</p>
</div>

<div class="card">
  <h2>💧 Humidity</h2>
  <p id="hum">-- %</p>
</div>

<script>
const url =
  "https://api.thingspeak.com/channels/3272751/feeds.json?api_key=YOUR_READ_API_KEY&results=1";

function fetchData() {
  fetch(url)
    .then(res => res.json())
    .then(data => {
      const feed = data.feeds[0];
      document.getElementById("temp").innerText = feed.field1 + " °C";
      document.getElementById("hum").innerText = feed.field2 + " %";
    });
}

fetchData();
setInterval(fetchData, 5000);  // Refresh every 5 seconds
</script>

</body>
</html>

Code Explanation

PartWhat It Does
fetch(url)Makes HTTP GET request to ThingSpeak REST API
feeds.json?results=1Gets only the latest 1 entry from the channel
feed.field1Temperature value from ThingSpeak Field 1
feed.field2Humidity value from ThingSpeak Field 2
setInterval(fetchData, 5000)Auto-refreshes data every 5 seconds
⚠️ Replace in the code:
3272751 → Your actual Channel ID
YOUR_READ_API_KEY → Your actual Read API Key

📱 Dashboard Preview

https://yourusername.github.io/iot-dashboard/

🌍 IoT Temperature & Humidity Dashboard

🌡 Temperature

28 °C

💧 Humidity

64 %

Commit this index.html file to your GitHub repository.

8

🚀 Enable GitHub Pages

Go to your repository on GitHub
Click Settings (top tab)
In the left sidebar, click Pages
Under Source, select:
Branch: main
Folder: / (root)
Click Save
🎉 You get a link like:
https://yourusername.github.io/iot-dashboard/

This is your live dashboard URL — accessible from anywhere in the world! 🌍
Note: It may take 1-2 minutes for GitHub Pages to deploy. Refresh the page if it doesn't load immediately.
9

🔗 Connect Everything in ThingSpeak

Go to your ThingSpeak Channel Settings and add these links:

SettingValue
Link to External Site https://yourusername.github.io/iot-dashboard/
Link to GitHub https://github.com/yourusername/iot-dashboard
📌 This links your cloud channel to your live dashboard and source code, making it a complete, connected ecosystem.
10

🔄 FINAL DATA FLOW (MEMORIZE THIS)

🌡️ DHT11 Sensor
Reads temperature & humidity
🍇 Raspberry Pi (Python)
Processes & sends via HTTP POST
Write API Key
☁️ ThingSpeak Cloud
Stores data, provides REST API
Read API Key
🌐 GitHub Pages (HTML Dashboard)
Fetches data via JavaScript fetch()
📱💻🖥️ Any Device — Anywhere!
Phone, PC, Tablet — with just a URL

🏆 YOU HAVE NOW BUILT A COMPLETE STANDALONE IoT PROJECT

🧰 Complete Technology Map

LayerTechnologyRole
Sensor LayerDHT11Measures temperature & humidity
Edge DeviceRaspberry PiReads sensor, processes, sends to cloud
ProgrammingPythonDevice-side scripting
ProtocolHTTP POST / GETData transmission
Cloud PlatformThingSpeakData storage + REST API
FrontendHTML + JavaScriptDashboard UI
HostingGitHub PagesFree static site hosting
AccessAny BrowserView from phone, PC, tablet

🎯 Skills Mastered

GPIO Interfacing Python Programming DHT11 Sensor HTTP REST API ThingSpeak Cloud GitHub Pages JavaScript Fetch IoT Architecture Live Dashboard End-to-End IoT

🚀 Possible Enhancements

EnhancementHow
Add more sensorsConnect BMP280, MQ-2 — add more fields in ThingSpeak
Add chartsUse Chart.js or ThingSpeak iframe widgets in your HTML
Add alertsUse ThingSpeak React app or IFTTT for email/SMS alerts
Use MQTTSwitch from HTTP to MQTT for faster, lighter communication
Add databaseUse Firebase or MongoDB for extended data storage
Mobile appBuild a Flutter/React Native app using the same API
Run on bootAdd Python script to crontab so it starts automatically

🔁 Auto-Start on Boot (Bonus)

Terminal
# Open crontab editor
crontab -e

# Add this line at the bottom:
@reboot python3 /home/pi/iot-project/send_to_thingspeak.py &
This ensures the Python script starts automatically every time the Raspberry Pi boots up — no manual intervention needed!