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

NoteEdge vs Cloud Processing
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:

  1. EDGE mode: All processing happens locally on the ESP32 in microseconds
  2. CLOUD mode: Simulates cloud round-trip with 150-400ms artificial latency
  3. 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

TipStep 1: Create the Circuit
  1. Open the Wokwi simulator above
  2. Add components from the parts panel
  3. Wire according to the circuit diagram
  4. Double-check all connections
TipStep 2: Run and Observe
  1. Click “Start Simulation”
  2. Open the Serial Monitor
  3. Observe the default HYBRID mode:
    • Green LED blinks: Edge processing (microseconds)
    • Blue LED blinks: Cloud processing (hundreds of milliseconds)
  4. Note how edge is 1000-10000x faster than cloud
TipStep 3: Test Different Modes
  1. Type E - Edge-only mode
  2. Type C - Cloud-only mode
  3. Type H - Hybrid mode
  4. Type S - View statistics
TipStep 4: Trigger Alerts
  1. Click on the NTC temperature sensor
  2. Adjust temperature slider above 30C (warning)
  3. Watch the Red LED illuminate
  4. Increase above 35C (critical)
  5. Notice the Red LED blinks rapidly

332.2.7 Expected Outcomes

ImportantKey Observations
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

  1. Store last 10 temperature readings
  2. Only send aggregated data (min, max, avg) to cloud every 10 readings
  3. Continue real-time edge threshold monitoring

Learning: Edge aggregation reduces bandwidth by 90%+.

Objective: Implement latency budget enforcement for safety-critical system

  1. Add const unsigned long LATENCY_BUDGET_US = 50000;
  2. Check if latency exceeded budget after each processing
  3. Track how often each mode meets the budget

Learning: Latency budgets determine when edge processing is mandatory.

Objective: Add intermediate fog processing tier

  1. Add MODE_FOG with 20-50ms simulated latency
  2. Fog aggregates from multiple “sensors”
  3. 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

NoteWhy Aggregation Matters

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

  1. Multi-sensor aggregation: Combine readings from temperature, light, and humidity sensors
  2. Statistical summarization: Calculate min, max, average, standard deviation locally
  3. Anomaly detection: Flag unusual readings at the edge without cloud
  4. Bandwidth optimization: Send only aggregated summaries instead of raw data
  5. 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

  1. 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
  2. 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
  3. 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
  4. 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.

Return to Edge and Fog Computing Overview –>