Here is a full smart-home version of the Raspberry Pi temperature & humidity monitor, upgraded into a real IoT mini–smart-home system with:

βœ” Live dashboard (web interface using Flask)
βœ” Real-time charts (auto-updated)
βœ” Alerts by email

This is still beginner-friendly, but powerful.

πŸ“¦ 1. Required Hardware

ComponentDetail
Raspberry Pi 3/4/5Any model works
DHT22 (recommended)Or DHT11
Jumper wires3
(Optional) BreadboardFor stability

πŸ”Œ 2. Wiring

Same as this tutorial : build Temperature & Humidity Monitor

DHT22 PinRaspberry Pi
VCC3.3V
DATAGPIO 4
GNDGND

πŸ’Ύ 3. Install Required Software

Install libraries

sudo apt update
sudo apt install python3-pip
pip3 install Adafruit_DHT flask flask_cors matplotlib pandas

πŸ“ 4. Project Structure

Create a folder:

mkdir smart_home
cd smart_home

Inside, create:

smart_home/
 β”œβ”€β”€ app.py            # Flask server
 β”œβ”€β”€ sensor.py         # Reads DHT22 sensor
 β”œβ”€β”€ static/
 β”‚     β”œβ”€β”€ chart.js    # Chart.js library
 β”‚     └── dashboard.js  
 └── templates/
       └── dashboard.html

πŸ“‘ 5. sensor.py β€” Read the Sensor & Save Data

import Adafruit_DHT
import time
import pandas as pd
from datetime import datetime

sensor = Adafruit_DHT.DHT22
pin = 4

def read_sensor():
    humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
    if humidity and temperature:
        return round(temperature, 1), round(humidity, 1)
    else:
        return None, None

def log_data():
    temperature, humidity = read_sensor()
    if temperature is None:
        return

    now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    df = pd.DataFrame([[now, temperature, humidity]],
                      columns=["time", "temp", "humidity"])
    df.to_csv("data.csv", mode="a", header=False, index=False)

This creates a data.csv file storing all readings β†’ used for charts.

🌐 6. app.py β€” Web Dashboard API (Flask)

from flask import Flask, render_template, jsonify
from sensor import read_sensor, log_data
import pandas as pd
import threading
import time

app = Flask(__name__)

# Background thread to log data every 60 seconds
def background_logging():
    while True:
        log_data()
        time.sleep(60)

threading.Thread(target=background_logging, daemon=True).start()

@app.route("/")
def dashboard():
    return render_template("dashboard.html")

@app.route("/live")
def live():
    temp, hum = read_sensor()
    return jsonify({"temp": temp, "humidity": hum})

@app.route("/history")
def history():
    df = pd.read_csv("data.csv", names=["time", "temp", "humidity"])
    return df.to_json(orient="records")

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=5000)

πŸ–₯ 7. templates/dashboard.html β€” Live Dashboard UI

<!DOCTYPE html>
<html>
<head>
    <title>Smart Home Dashboard</title>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
    <h1>Smart Home - Temperature & Humidity</h1>

    <h2>Live Data</h2>
    <p>Temperature: <span id="temp">--</span> Β°C</p>
    <p>Humidity: <span id="hum">--</span> %</p>

    <canvas id="chart" width="500" height="200"></canvas>

    <script src="/static/dashboard.js"></script>
</body>
</html>

πŸ“Š 8. static/dashboard.js β€” Real-Time Chart + Live Updates

// Fetch live values every 2 seconds
setInterval(async () => {
    let r = await fetch("/live");
    let data = await r.json();
    document.getElementById("temp").innerText = data.temp;
    document.getElementById("hum").innerText = data.humidity;
}, 2000);

// Load chart history
async function loadChart() {
    let r = await fetch("/history");
    let data = await r.json();

    let times = data.map(d => d.time);
    let temps = data.map(d => d.temp);

    new Chart(document.getElementById('chart'), {
        type: "line",
        data: {
            labels: times,
            datasets: [{
                label: "Temperature Β°C",
                data: temps,
                borderWidth: 2
            }]
        }
    });
}

loadChart();

🚨 9. Add Alerts (Email or Telegram)

βœ” Email alert (using Gmail or Brevo API)

Install:

pip3 install yagmail

Add a function in sensor.py:

import yagmail

def send_alert(temp):
    yag = yagmail.SMTP("YOUR_EMAIL@gmail.com", "YOUR_APP_PASSWORD")
    yag.send(
        to="YOUR_EMAIL@gmail.com",
        subject="πŸ”₯ High Temperature Alert!",
        contents=f"Warning! Temperature reached {temp}Β°C",
    )

Trigger:

if temperature > 30:
    send_alert(temperature)

βœ… Full sensor.py (with alert system integrated)

import Adafruit_DHT
import time
import pandas as pd
from datetime import datetime
import yagmail   # Only if you use email alerts

# ---- SENSOR CONFIG ----
sensor = Adafruit_DHT.DHT22
pin = 4   # GPIO 4

# ---- EMAIL ALERT CONFIG ----
EMAIL_SENDER = "YOUR_EMAIL@gmail.com"
EMAIL_PASSWORD = "YOUR_APP_PASSWORD"
EMAIL_RECEIVER = "RECEIVER_EMAIL@gmail.com"

def send_alert(temp):
    """Send email alert when temperature exceeds threshold."""
    try:
        yag = yagmail.SMTP(EMAIL_SENDER, EMAIL_PASSWORD)
        subject = "πŸ”₯ High Temperature Alert!"
        message = f"Warning! Temperature reached {temp}Β°C"
        yag.send(to=EMAIL_RECEIVER, subject=subject, contents=message)
        print(f"[ALERT SENT] Temperature = {temp}Β°C")
    except Exception as e:
        print("[ERROR] Could not send alert:", e)

# ---- READ SENSOR ----
def read_sensor():
    """Read temperature & humidity from DHT22."""
    humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
    
    if humidity is not None and temperature is not None:
        temperature = round(temperature, 1)
        humidity = round(humidity, 1)
        return temperature, humidity
    else:
        return None, None

# ---- LOG DATA + ALERT ----
def log_data():
    """Read sensor, send alert if needed, and save data."""
    temperature, humidity = read_sensor()

    # Ignore failed reads
    if temperature is None:
        print("[WARNING] Failed to read sensor β€” skipping...")
        return

    # ---- πŸ”₯ ALERT TRIGGER ----
    if temperature > 30:
        send_alert(temperature)

    # ---- SAVE TO CSV ----
    now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    df = pd.DataFrame([[now, temperature, humidity]],
                      columns=["time", "temp", "humidity"])
    df.to_csv("data.csv", mode="a", header=False, index=False)

    print(f"[LOGGED] {now}  Temp={temperature}Β°C  Hum={humidity}%")

πŸ“Œ Notes You Must Update

Before running the script, edit these lines:

EMAIL_SENDER = "YOUR_EMAIL@gmail.com"
EMAIL_PASSWORD = "YOUR_APP_PASSWORD"
EMAIL_RECEIVER = "RECEIVER_EMAIL@gmail.com"

⚠ Gmail requires an App Password (not your real login). 

βœ… 10. Start the Flask Server

Go to your project folder:

cd smart_home

Run:

python3 app.py

You should see something like:

 * Running on http://0.0.0.0:5000
 * Logging thread started...

πŸ“± 10. Access the Dashboard From Your Phone

On your Raspberry Pi OR another device (phone/laptop), open:

http://RASPBERRY_PI_IP:5000

Example:

http://192.168.1.30:5000

Find your Pi’s IP address with:

hostname -I

You'll now see:

πŸŽ‰ Result: What You Have Built

βœ” A real IoT smart-home monitoring system
βœ” Live temperature & humidity readings
βœ” Beautiful charts (past 24h / week)
βœ” Automatic data logging
βœ” Email alerts
βœ” Mobile-friendly dashboard
βœ” Expandable to motion sensors, lighting, relays, cameras…