Objective: Build a containerized web application that displays real-time temperature data from multiple sources in an interactive dashboard.
What You'll Build:
Skills Applied: Microcontroller programming, web development, API integration, containerization, and real-time data visualization
Sensors You'll Use:
Reference Materials:
Your Task: Write Arduino code that reads both sensors and sends temperature data via Serial in a structured format (e.g., JSON or CSV)
💡 Tip: Use JSON, one reading per line: {"dht":25.5,"mf52":25.3}. Python can parse it with json.loads() (next slide).
Recommended Serial Output Format:
Your Arduino should continuously output temperature readings in a parseable format. Here's an example:
💡 Pro Tips:
void loop() {
float dht_temp = dht.readTemperature();
float mf52_temp = readMF52Temperature();
// JSON format (recommended)
Serial.print("{\"dht\":");
Serial.print(dht_temp);
Serial.print(",\"mf52\":");
Serial.print(mf52_temp);
Serial.println("}");
delay(2000);
}
Technology Stack (what we use):
How data flows: every 2 seconds, Python reads the sensors, then pushes the numbers to every open browser. The browser draws them on the charts. No page refresh needed.
┌──────────┐ USB/Serial ┌─────────────────────┐
│ Arduino │ ────────────▶ │ Flask (app.py) │
│ DHT11 │ {"dht":25.5, │ │
│ MF52A │ "mf52":25.3}│ read_arduino() ✏️ │
└──────────┘ │ get_outdoor_temp()✏️│◀── Weather API
│ │
│ broadcast_loop() 📋│
└─────────┬───────────┘
│ WebSocket
│ 'sensor_data'
┌─────────▼───────────┐
│ Browser │
│ index.html 📋 │
│ style.css 📋 │
│ dashboard.js 📋 │
│ (3 live charts) │
└─────────────────────┘
WebSockets and JavaScript were not covered in class, so the whole frontend and the WebSocket "glue" are provided. You copy them, read the explanations, and focus on the parts you have learned.
| File / Part | Status |
|---|---|
templates/index.html | 📋 COPY AS-IS |
static/style.css | 📋 COPY AS-IS |
static/dashboard.js | 📋 COPY AS-IS |
app.py: Flask + WebSocket setup, broadcast loop | 🧩 COPY + FILL IN TODOs |
arduino/sensor_reader.ino | ✏️ YOU BUILD THIS |
read_arduino(): serial reading + JSON parsing | ✏️ YOU BUILD THIS |
get_outdoor_temp(): weather API + caching | ✏️ YOU BUILD THIS |
requirements.txt, Dockerfile, docker-compose.yml, .env | ✏️ YOU BUILD THIS |
💡 Grading focus: the hardware, the Python backend logic, error handling, and containerization. You are not expected to modify the JavaScript (but you may customise it if you want!).
Same layout as the Week 12 To-Do app: Flask looks for HTML in templates/ and for CSS/JS in static/. The folder names are not optional!
Setup:
mkdir temperature-monitor
cd temperature-monitor
python -m venv venv
# activate venv (see Week 12), then:
pip install flask flask-socketio simple-websocket pyserial requests
pip freeze > requirements.txt
💡 Tip: create all the empty files and folders first, then fill them in using the next slides.
temperature-monitor/
├── arduino/
│ └── sensor_reader.ino ✏️ you write
├── templates/
│ └── index.html 📋 copy
├── static/
│ ├── style.css 📋 copy
│ └── dashboard.js 📋 copy
├── app.py 🧩 copy + fill TODOs
├── requirements.txt ✏️ you create
├── .env ✏️ you create (never commit!)
├── Dockerfile ✏️ you write
└── docker-compose.yml ✏️ you write
Using PySerial Library:
Install with: pip install pyserial
💡 Important Tips:
/dev/ttyUSB0, /dev/ttyACM0 (Linux/Mac) or COM3, COM4 (Windows)json.loads() in try/except: the first line after connecting is often half a line!read_arduino() function in app.pyimport serial
import serial.tools.list_ports
import json
def find_arduino_port():
"""Auto-detect Arduino port"""
ports = serial.tools.list_ports.comports()
for port in ports:
# Look for Arduino in description
if 'Arduino' in port.description or \
'USB' in port.description:
return port.device
return None
# Auto-detect or use environment variable
port = find_arduino_port() or '/dev/ttyUSB0'
ser = serial.Serial(port, 9600, timeout=1)
def read_arduino_data():
if ser.in_waiting > 0:
line = ser.readline().decode('utf-8').strip()
data = json.loads(line)
return {'dht': data['dht'], 'mf52': data['mf52']}
return None
Reference Your Previous Learning:
Refer back to your weather API slides for details on API keys, endpoints, and data parsing.
Your Task:
get_outdoor_temp() function in app.py; return a float or None💡 Best Practices:
last_value and last_time; only call the API again if time.time() - last_time > 600Normal HTTP (what you know): the browser asks, the server answers, the connection closes. To get new data the browser has to ask again and again.
WebSocket: the browser opens a connection once and keeps it open. Now the server can push new data whenever it wants. Perfect for live sensor readings!
Socket.IO is a library that makes WebSockets easy. It works with named events:
socketio.emit('sensor_data', {...})socket.on('sensor_data', (data) => {...})💡 That's all you need to understand. The code that does this is provided on the next slides.
HTTP (request / response)
Browser ── "give me data?" ──▶ Server
Browser ◀──── "25.5" ──────── Server
(connection closed, ask again...)
WebSocket (always open)
Browser ════ open once ═════▶ Server
Browser ◀── sensor_data ───── Server
Browser ◀── sensor_data ───── Server
Browser ◀── sensor_data ───── Server
(every 2 seconds)
The provided frontend expects your backend to send an event called sensor_data containing a dictionary with exactly these keys:
| Key | Type | Meaning |
|---|---|---|
dht | float or None | DHT11 temperature (°C) |
mf52 | float or None | MF52A temperature (°C) |
outdoor | float or None | Temperature from the weather API (°C) |
time | string | Timestamp shown on the x-axis |
If a value is None, the chart simply skips that point and shows --.
💡 Good news: the provided broadcast_loop() in app.py already builds this dictionary. Your functions just have to return the right numbers.
# Python side (already in app.py)
socketio.emit("sensor_data", {
"dht": 25.5,
"mf52": 25.3,
"outdoor": 18.2,
"time": "14:05:32",
})
# JavaScript side (already in dashboard.js)
# socket.on('sensor_data', (data) => {
# data.dht -> 25.5
# data.mf52 -> 25.3
# data.outdoor -> 18.2
# data.time -> "14:05:32"
# })
templates/index.htmlThe page skeleton: a header, three panels, and the scripts.
id="dhtValue") and a <canvas> where Chart.js draws the chart{{ url_for('static', ...) }} is Jinja2 (Week 12): it builds the link to files in static/dashboard.js is loaded last, so the page and libraries exist before it runs💡 The id values must match the ones used in dashboard.js. Don't rename them.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Temperature Monitor</title>
<!-- url_for() finds the file inside the static/ folder -->
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
<header>
<h1>🌡️ Real-Time Temperature Monitor</h1>
<span id="status" class="status">● Disconnected</span>
</header>
<main class="grid">
<!-- Panel 1: DHT11 -->
<section class="panel">
<h2>DHT11 Sensor</h2>
<div class="value" id="dhtValue">--</div>
<div class="chart-box"><canvas id="dhtChart"></canvas></div>
</section>
<!-- Panel 2: MF52A -->
<section class="panel">
<h2>MF52A Thermistor</h2>
<div class="value" id="mf52Value">--</div>
<div class="chart-box"><canvas id="mf52Chart"></canvas></div>
</section>
<!-- Panel 3: Outdoor (Weather API) -->
<section class="panel">
<h2>Outdoor (Weather API)</h2>
<div class="value" id="outdoorValue">--</div>
<div class="chart-box"><canvas id="outdoorChart"></canvas></div>
</section>
</main>
<footer>Last update: <span id="lastUpdate">--</span></footer>
<!-- Libraries (loaded from the internet) -->
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.1/dist/chart.umd.min.js"></script>
<script src="https://cdn.socket.io/4.7.5/socket.io.min.js"></script>
<!-- Our dashboard code (must be loaded LAST) -->
<script src="{{ url_for('static', filename='dashboard.js') }}"></script>
</body>
</html>
static/style.cssMakes the dashboard look nice. Nothing here affects how the data works.
.grid uses CSS Grid: the 3 panels sit side by side, and wrap on a small screen.chart-box gives each chart a fixed height (Chart.js needs this).status.connected turns the status text green when the WebSocket connects🎨 Optional: this is the safest file to personalise: change colours, fonts, sizes.
/* style.css: dashboard look & feel (provided) */
body {
margin: 0;
font-family: "Segoe UI", Roboto, Arial, sans-serif;
background: #f1f4f9;
color: #2d3436;
}
header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 16px 32px;
background: #2d3436;
color: white;
}
header h1 { margin: 0; font-size: 1.5rem; }
.status { font-weight: bold; color: #ff7675; } /* red */
.status.connected { color: #55efc4; } /* green */
/* 3 panels side by side; they wrap on small screens */
.grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(320px, 1fr));
gap: 20px;
padding: 24px 32px;
}
.panel {
background: white;
border-radius: 12px;
padding: 16px 20px;
box-shadow: 0 4px 14px rgba(0, 0, 0, 0.08);
}
.panel h2 { margin: 0 0 4px; font-size: 1.1rem; color: #636e72; }
.value { font-size: 2.4rem; font-weight: bold; margin-bottom: 8px; }
.chart-box { position: relative; height: 260px; }
footer { text-align: center; color: #636e72; padding-bottom: 24px; }
static/dashboard.jsThe "brain" of the page. It has 4 parts (explained on the next slide):
sensor_data and update everything💡 Scroll inside the code box to see the whole file, or just press Copy.
// dashboard.js: PROVIDED CODE. Copy it as-is.
// It connects to your Flask server with a WebSocket (Socket.IO)
// and draws the incoming temperatures on three Chart.js charts.
const MAX_POINTS = 50; // keep only the last 50 readings per chart
// ---------- 1. Create the three charts ----------
function createChart(canvasId, label, color) {
return new Chart(document.getElementById(canvasId), {
type: 'line',
data: {
labels: [], // x-axis: time stamps
datasets: [{
label: label,
data: [], // y-axis: temperatures
borderColor: color,
backgroundColor: color + '33', // same colour, transparent
fill: true,
tension: 0.3,
pointRadius: 2
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
animation: false,
scales: {
x: { title: { display: true, text: 'Time' } },
y: { title: { display: true, text: 'Temperature (°C)' } }
}
}
});
}
const dhtChart = createChart('dhtChart', 'DHT11', '#e17055');
const mf52Chart = createChart('mf52Chart', 'MF52A', '#0984e3');
const outdoorChart = createChart('outdoorChart', 'Outdoor', '#00b894');
// ---------- 2. Helper functions ----------
function addPoint(chart, time, value) {
if (value === null || value === undefined) return; // skip missing data
chart.data.labels.push(time);
chart.data.datasets[0].data.push(value);
if (chart.data.labels.length > MAX_POINTS) { // sliding window
chart.data.labels.shift();
chart.data.datasets[0].data.shift();
}
chart.update();
}
function showValue(elementId, value) {
const el = document.getElementById(elementId);
el.textContent = (value === null || value === undefined)
? '--'
: Number(value).toFixed(1) + ' °C';
}
// ---------- 3. Connect to the server (WebSocket) ----------
const socket = io(); // connects to the same server that served this page
const statusEl = document.getElementById('status');
socket.on('connect', () => {
statusEl.textContent = '● Connected';
statusEl.classList.add('connected');
});
socket.on('disconnect', () => {
statusEl.textContent = '● Disconnected';
statusEl.classList.remove('connected');
});
// ---------- 4. Receive data from the server ----------
// Python sends: socketio.emit('sensor_data', {...})
// data = { dht: 25.5, mf52: 25.3, outdoor: 18.2, time: '14:05:32' }
socket.on('sensor_data', (data) => {
const time = data.time || new Date().toLocaleTimeString();
addPoint(dhtChart, time, data.dht);
showValue('dhtValue', data.dht);
addPoint(mf52Chart, time, data.mf52);
showValue('mf52Value', data.mf52);
addPoint(outdoorChart, time, data.outdoor);
showValue('outdoorValue', data.outdoor);
document.getElementById('lastUpdate').textContent = time;
});
dashboard.js WorksJavaScript ↔ Python cheat-sheet (to help you read it):
| JavaScript | Python equivalent |
|---|---|
const x = 5; | x = 5 |
function addPoint(chart, t, v) { ... } | def add_point(chart, t, v): |
arr.push(v) / arr.shift() | lst.append(v) / lst.pop(0) |
data.dht | data["dht"] |
null | None |
(data) => { ... } | lambda data: ... (a small function) |
console.log(x) | print(x) (see it with F12 → Console) |
The key idea: socket.on('sensor_data', ...) is like a Flask route, but instead of the browser asking, the function runs every time Python emits that event.
// Part 1: one function creates any chart
const dhtChart = createChart('dhtChart', 'DHT11', '#e17055');
// Part 2: sliding window, keep last 50 points
chart.data.labels.push(time);
if (chart.data.labels.length > MAX_POINTS) {
chart.data.labels.shift(); // drop the oldest
}
// Part 3: connect (to the server that served the page)
const socket = io();
socket.on('connect', () => { /* show "Connected" */ });
// Part 4: runs every time Python does
// socketio.emit("sensor_data", {...})
socket.on('sensor_data', (data) => {
addPoint(dhtChart, data.time, data.dht);
showValue('dhtValue', data.dht);
// ... same for mf52 and outdoor
});
app.py StarterCopy this file. The Flask + WebSocket parts are done for you. You only fill in the two functions marked TODO:
read_arduino(): return (dht, mf52) using your PySerial code (Step 1b)get_outdoor_temp(): return the outdoor temperature using your weather API code (Step 3)What the provided part does:
SocketIO(app) adds WebSocket support to Flaskbroadcast_loop() runs in the background, calls your two functions every 2 s and emits sensor_datasocketio.run(...) replaces app.run(...); host="0.0.0.0" is needed for Docker💡 You may move your functions to serial_reader.py / weather_api.py and import them. Good structure earns marks!
# app.py: Temperature Monitor backend
import os
import time
from flask import Flask, render_template
from flask_socketio import SocketIO
app = Flask(__name__)
socketio = SocketIO(app, cors_allowed_origins="*") # PROVIDED
SERIAL_PORT = os.getenv("SERIAL_PORT", "/dev/ttyUSB0")
WEATHER_API_KEY = os.getenv("WEATHER_API_KEY")
# ===================== YOUR CODE =====================
def read_arduino():
"""TODO (Step 1): read ONE line from the serial port,
parse the JSON and return (dht, mf52) as floats.
Return (None, None) if there is no valid reading."""
return None, None
def get_outdoor_temp():
"""TODO (Step 3): return the outdoor temperature (float)
from the weather API. Cache it: only call the API every
5-10 minutes! Return None if the API fails."""
return None
# =====================================================
# ============ PROVIDED: WebSocket broadcast ==========
def broadcast_loop():
"""Runs forever in the background. Every 2 seconds it
pushes the latest readings to every open browser."""
while True:
dht, mf52 = read_arduino()
outdoor = get_outdoor_temp()
if dht is not None or mf52 is not None:
socketio.emit("sensor_data", {
"dht": dht,
"mf52": mf52,
"outdoor": outdoor,
"time": time.strftime("%H:%M:%S"),
})
socketio.sleep(2)
@app.route("/")
def index():
return render_template("index.html")
@socketio.on("connect")
def on_connect():
print("Browser connected")
if __name__ == "__main__":
socketio.start_background_task(broadcast_loop)
socketio.run(app, host="0.0.0.0", port=8000,
allow_unsafe_werkzeug=True)
Before touching the Arduino, check that the copied frontend works. Temporarily make your functions return random numbers:
Then:
python app.pyNot working?
TemplateNotFound: check the templates/ folder namestatic/ folder and file names✅ Once this works, replace the fake data with your real serial + API code.
import random
def read_arduino():
# FAKE DATA - for testing only!
dht = round(random.uniform(20, 30), 1)
mf52 = round(random.uniform(20, 30), 1)
return dht, mf52
def get_outdoor_temp():
# FAKE DATA - for testing only!
return 18.2
Why Containerize?
Prerequisites:
💡 Development Tip: Always test your app locally before containerizing. Debug Docker issues separately from application bugs!
Basic Dockerfile Structure:
This example is for a Python Flask application
💡 Key Points:
.dockerignore with venv/ and .env so they are not copiedFROM python:3.10-slim
WORKDIR /app
# Install dependencies
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# Copy application code
# (app.py, templates/, static/)
COPY . .
# Expose port
EXPOSE 8000
# Run the application
CMD ["python", "app.py"]
The Challenge: Docker containers are isolated from your host's hardware. You must explicitly give the container access to the serial port.
Step 1: Find Your Arduino Port
ls /dev/tty* or ls /dev/cu.*Step 2: Add Device Mapping to Docker Command
Use the --device flag to map the serial port:
docker run --device=/dev/ttyUSB0:/dev/ttyUSB0 your-image
💡 Important: The port path inside the container (after the colon) should match what your code expects!
Docker Compose makes running containers easier:
Key Configuration:
devices: Map the serial portprivileged: May be needed for serial access (use cautiously)ports: Expose web application portRun with: docker-compose up
version: '3.8'
services:
temp-monitor:
build: .
ports:
- "8000:8000"
devices:
- "/dev/ttyUSB0:/dev/ttyUSB0"
environment:
- SERIAL_PORT=/dev/ttyUSB0
- WEATHER_API_KEY=${WEATHER_API_KEY}
# Optional: if serial access issues persist
# privileged: true
Common Issues & Solutions:
Problem 1: Permission Denied
sudo usermod -a -G dialout $USERProblem 2: Port Not Found
ls -l /dev/ttyUSB*Problem 3: Port Name Changes
💡 Debug Tip: Test serial communication outside Docker first, then troubleshoot Docker-specific issues
Build Process:
💡 Testing Checklist:
# Build the Docker image
docker build -t temp-monitor .
# Run with serial port mapping
docker run -p 8000:8000 \
--device=/dev/ttyUSB0:/dev/ttyUSB0 \
-e WEATHER_API_KEY=your_key_here \
temp-monitor
# Or use docker-compose
docker-compose up
# Access in browser
# http://localhost:8000
Never hardcode sensitive information!
Create a .env file:
💡 Security Tips:
# .env file (don't commit this!)
WEATHER_API_KEY=abc123xyz789
SERIAL_PORT=/dev/ttyUSB0
BAUD_RATE=9600
# .env.example (commit this)
WEATHER_API_KEY=your_api_key_here
SERIAL_PORT=/dev/ttyUSB0
BAUD_RATE=9600
# Access in Python
import os
api_key = os.getenv('WEATHER_API_KEY')
Before Submission, Verify:
✓ Hardware Layer:
✓ Software Layer:
✓ Containerization:
🚫 Don't Do This:
sensor_data and keys dht, mf52, outdoor, time must match the provided JavaScripttemplates/ and static/app.run(): with WebSockets you must start the server with socketio.run()✅ Do This Instead: Plan your architecture, test incrementally, handle errors gracefully, document as you go!