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.
| Component | Detail |
|---|---|
| Raspberry Pi 3/4/5 | Any model works |
| DHT22 (recommended) | Or DHT11 |
| Jumper wires | 3 |
| (Optional) Breadboard | For stability |
Same as this tutorial : build Temperature & Humidity Monitor
| DHT22 Pin | Raspberry Pi |
|---|---|
| VCC | 3.3V |
| DATA | GPIO 4 |
| GND | GND |
Install libraries
sudo apt update
sudo apt install python3-pip
pip3 install Adafruit_DHT flask flask_cors matplotlib pandas
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
sensor.py β Read the Sensor & Save Dataimport 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.
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)
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>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();
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}%")
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).
Go to your project folder:
cd smart_homeRun:
python3 app.pyYou should see something like:
* Running on http://0.0.0.0:5000
* Logging thread started...
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 -IYou'll now see:
/live API)β 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β¦