332 Edge and Fog Computing: Hands-On Labs
332.1 Learning Objectives
By the end of these labs, you will be able to:
- Compare edge vs cloud latency: Measure response time differences in real hardware
- Implement threshold-based edge processing: Create autonomous edge decisions
- Build hybrid architectures: Learn when to process locally vs offload to cloud
- Measure bandwidth savings: Quantify how edge aggregation reduces data transmission
- Design resilient systems: Create IoT solutions that continue operating during outages
332.2 Lab 1: Build an Edge Computing Demo
This hands-on lab demonstrates the fundamental difference between edge and cloud processing using an ESP32 microcontroller. You will implement both processing models and observe the dramatic latency differences in real-time.
332.2.1 Components
| Component | Purpose | Wokwi Element |
|---|---|---|
| ESP32 DevKit | Main controller with edge processing logic | esp32:devkit-v1 |
| Temperature Sensor (NTC) | Simulates sensor input for threshold detection | ntc-temperature-sensor |
| Green LED | Indicates EDGE processing (fast local decision) | led:green |
| Blue LED | Indicates CLOUD processing (slow remote decision) | led:blue |
| Red LED | Indicates ALERT state (threshold exceeded) | led:red |
| Resistors (3x 220 ohm) | Current limiting for LEDs | resistor |
332.2.2 Key Concepts
| Aspect | Edge Processing | Cloud Processing |
|---|---|---|
| Latency | 1-10 ms | 100-500+ ms |
| Network Required | No | Yes |
| Processing Power | Limited | Unlimited |
| Reliability | Works offline | Depends on connectivity |
| Use Case | Time-critical alerts | Complex analytics |
Real-world impact: In industrial safety, a 500ms delay detecting a dangerous temperature could mean the difference between a controlled shutdown and equipment damage. Edge processing enables sub-10ms response times.
332.2.3 Interactive Wokwi Simulator
Use the embedded simulator below to build and test your edge computing demo. Click “Start Simulation” after entering the code.
332.2.4 Circuit Connections
ESP32 Pin Connections:
---------------------
GPIO 2 --> Green LED (+) --> 220 ohm Resistor --> GND [EDGE indicator]
GPIO 4 --> Blue LED (+) --> 220 ohm Resistor --> GND [CLOUD indicator]
GPIO 5 --> Red LED (+) --> 220 ohm Resistor --> GND [ALERT indicator]
GPIO 34 --> NTC Temperature Sensor (Signal pin)
NTC VCC --> 3.3V
NTC GND --> GND
332.2.5 Code Overview
The lab code demonstrates three processing modes:
- EDGE mode: All processing happens locally on the ESP32 in microseconds
- CLOUD mode: Simulates cloud round-trip with 150-400ms artificial latency
- HYBRID mode: Edge handles time-critical alerts, cloud handles logging
Key code structure:
// Processing mode options
enum ProcessingMode {
MODE_EDGE, // Local processing only (~1-50 microseconds)
MODE_CLOUD, // Simulated cloud processing (~150-400 ms)
MODE_HYBRID // Edge for alerts, cloud for logging
};
// Edge processing - instant response
void processAtEdge(float temperature) {
unsigned long startTime = micros();
// All computation happens RIGHT HERE on the ESP32
if (temperature >= TEMP_CRITICAL) {
// IMMEDIATE action - no network delay
triggerEmergencyShutdown();
}
unsigned long edgeLatency = micros() - startTime;
// Typical: 5-50 microseconds
}
// Cloud processing - significant delay
void processAtCloud(float temperature) {
unsigned long startTime = micros();
// Simulate network round-trip
delay(random(150, 400)); // 150-400ms latency
// Same logic, but AFTER the delay
if (temperature >= TEMP_CRITICAL) {
// Response delayed by network latency
triggerEmergencyShutdown();
}
unsigned long cloudLatency = micros() - startTime;
// Typical: 150,000-400,000 microseconds
}332.2.6 Step-by-Step Instructions
- Open the Wokwi simulator above
- Add components from the parts panel
- Wire according to the circuit diagram
- Double-check all connections
- Click “Start Simulation”
- Open the Serial Monitor
- Observe the default HYBRID mode:
- Green LED blinks: Edge processing (microseconds)
- Blue LED blinks: Cloud processing (hundreds of milliseconds)
- Note how edge is 1000-10000x faster than cloud
- Type
E- Edge-only mode - Type
C- Cloud-only mode - Type
H- Hybrid mode - Type
S- View statistics
- Click on the NTC temperature sensor
- Adjust temperature slider above 30C (warning)
- Watch the Red LED illuminate
- Increase above 35C (critical)
- Notice the Red LED blinks rapidly
332.2.7 Expected Outcomes
| Metric | Expected Value | Significance |
|---|---|---|
| Edge latency | < 500 microseconds | 1000x faster than cloud |
| Cloud latency | 150-450 milliseconds | Network dominates total time |
| Bandwidth reduction | 95-99% | Only aggregates sent to cloud |
| Alert response | < 1 millisecond | Safety-critical capability |
| Offline operation | Fully functional | Resilience during outages |
Real-World Applications:
- Smart Factory: Aggregate vibration data from 1000 sensors, only send anomalies to cloud
- Smart Building: Process HVAC data locally, optimize energy without cloud latency
- Healthcare Monitoring: Detect arrhythmias at the edge in <5ms
- Autonomous Vehicles: Process LIDAR/camera locally, make decisions in <20ms
332.2.8 Challenge Exercises
Objective: Demonstrate edge computing’s reliability advantage
Modify the code to simulate network failures: 1. Add bool networkAvailable = true; 2. Add command ‘N’ to toggle network availability 3. When unavailable, cloud mode shows “NETWORK ERROR” 4. Edge mode continues working normally
Learning: Edge computing provides resilience during outages.
Objective: Reduce cloud traffic through edge aggregation
- Store last 10 temperature readings
- Only send aggregated data (min, max, avg) to cloud every 10 readings
- Continue real-time edge threshold monitoring
Learning: Edge aggregation reduces bandwidth by 90%+.
Objective: Implement latency budget enforcement for safety-critical system
- Add
const unsigned long LATENCY_BUDGET_US = 50000; - Check if latency exceeded budget after each processing
- Track how often each mode meets the budget
Learning: Latency budgets determine when edge processing is mandatory.
Objective: Add intermediate fog processing tier
- Add
MODE_FOGwith 20-50ms simulated latency - Fog aggregates from multiple “sensors”
- Add Yellow LED indicator for fog processing
Learning: Fog provides intermediate processing between edge and cloud.
332.3 Lab 2: Edge Data Aggregation and Smart Decision Making
This advanced lab demonstrates multi-sensor edge aggregation and autonomous decision making.
332.3.1 The Bandwidth Problem
A single sensor at 100 Hz generates: - Raw data: 100 samples/sec x 4 bytes = 34.5 MB/day - With 100 sensors: 3.45 GB/day = 103.5 GB/month
With edge aggregation (1-minute averages): - Aggregated data: 5.76 KB/day per sensor - With 100 sensors: 576 KB/day = 17.3 MB/month
Bandwidth reduction: 99.98%
332.3.2 Components
| Component | Purpose | Wokwi Element |
|---|---|---|
| ESP32 DevKit | Edge computing node | esp32:devkit-v1 |
| Temperature Sensor | Environmental monitoring | ntc-temperature-sensor |
| Light Sensor (LDR) | Ambient light detection | photoresistor-sensor |
| Potentiometer | Simulates humidity sensor | slide-potentiometer |
| Push Button | Manual cloud sync trigger | pushbutton |
| 4x LEDs | Status indicators | Various colors |
332.3.3 Key Concepts Demonstrated
- Multi-sensor aggregation: Combine readings from temperature, light, and humidity sensors
- Statistical summarization: Calculate min, max, average, standard deviation locally
- Anomaly detection: Flag unusual readings at the edge without cloud
- Bandwidth optimization: Send only aggregated summaries instead of raw data
- Offline resilience: Continue operating during network outages
332.3.4 Aggregation Algorithm
struct SensorAggregation {
float min;
float max;
float sum;
int count;
float sumSquares; // For standard deviation
void reset() {
min = FLT_MAX;
max = -FLT_MAX;
sum = 0;
count = 0;
sumSquares = 0;
}
void addReading(float value) {
if (value < min) min = value;
if (value > max) max = value;
sum += value;
sumSquares += value * value;
count++;
}
float getAverage() {
return count > 0 ? sum / count : 0;
}
float getStdDev() {
if (count < 2) return 0;
float avg = getAverage();
return sqrt((sumSquares / count) - (avg * avg));
}
};332.3.5 Reflection Questions
- Why is edge aggregation essential for IoT scale?
- A factory with 10,000 sensors at 100 Hz generates 1 GB/second raw
- Edge aggregation reduces to ~1 MB/second of insights
- Cloud bandwidth costs would be prohibitive otherwise
- How would you handle conflicting decisions between edge and cloud?
- Edge should win for safety-critical, time-sensitive decisions
- Cloud can override for business logic
- Implement hierarchy: Safety > Cloud policy > Edge defaults
- What happens when aggregation hides important details?
- Min/max preserve extremes even when average looks normal
- Standard deviation flags unusual variability
- Anomaly detection triggers full-resolution upload
- How would you extend this to support ML at the edge?
- Train models in cloud with historical aggregated data
- Deploy inference models to edge devices
- Edge runs prediction in microseconds, cloud retrains periodically
332.4 Summary
These hands-on labs demonstrate the fundamental principles of edge and fog computing:
- Edge processing provides 1000-10000x lower latency than cloud
- Aggregation reduces bandwidth by 95-99%
- Hybrid architectures provide the best of both worlds
- Edge computing enables offline resilience
332.5 What’s Next?
Return to the chapter overview to explore more edge and fog computing topics.