51  Lab: Network Packet Simulator

Key Concepts
  • Packet Simulator: Software (e.g., NS-3, Cooja, OMNeT++) that models network behaviour as discrete packet transmission events without physical hardware
  • Simulation Time: The simulated clock inside the simulator, which may run faster or slower than wall-clock time depending on model complexity
  • Radio Model: The simulator’s representation of wireless channel behaviour, including path loss, multipath, and interference
  • Mobility Model: A mathematical description of how nodes move over time during a simulation (e.g., random waypoint, Gauss-Markov)
  • Traffic Generator: A simulation component that creates packet flows at specified rates to load the simulated network
  • Trace File: A log of all simulated events (packet send, receive, drop) used for post-simulation analysis
  • Confidence Interval: A statistical range within which the true mean of a simulation metric lies with specified probability; computed over multiple independent runs

51.1 In 60 Seconds

This hands-on ESP32 lab simulates network packet transmission using LEDs to visualize packet states (transmitting, received, success, error). You will construct packets with headers, payloads, and checksums, then observe how error detection works in practice by introducing deliberate corruption and watching checksum verification catch the errors.

51.2 Learning Objectives

By completing this lab, you will be able to:

  • Construct a packet structure: Identify and explain the components of a network packet (header, payload, checksum) and build one in ESP32 C++ code
  • Demonstrate transmission states: Apply LED indicators to represent distinct stages of packet transmission through a finite state machine
  • Implement error detection: Calculate and verify checksums for data integrity using the ones’ complement algorithm (RFC 1071)
  • Analyze packet communication: Apply serial output inspection to identify transmission errors and differentiate between corrupted and valid packets
  • Calculate protocol overhead: Evaluate the trade-off between error detection strength (checksum vs CRC32) and bandwidth efficiency for constrained IoT links

A network packet is a small chunk of data that travels across a network, like a postcard traveling through the postal system. Each packet carries an address (header), the message itself (payload), and a verification stamp (checksum) to make sure nothing was damaged in transit. In this lab, you will simulate sending packets between devices, watching LEDs indicate what is happening at each step. It is a hands-on way to understand what normally happens invisibly inside your Wi-Fi network.

51.3 Browser-First Lab: Build and Break a Packet

Use this activity first. It teaches the same packet ideas without requiring an ESP32, breadboard, or external simulator. Change the payload size, packet rate, and corruption setting, then read how the header, payload, checksum, and link utilisation change.

Try It: Packet State Simulator

Use this after the browser simulator if you want to connect LEDs to real packet states: transmitting, received, valid, and error.

Component Quantity Purpose
ESP32 DevKit 1 Microcontroller for packet simulation
Red LED 1 Error indicator (checksum failure)
Green LED 1 Success indicator (valid packet)
Yellow LED 1 Transmission in progress
Blue LED 1 Packet received indicator
220 ohm Resistors 4 Current limiting for LEDs
Breadboard 1 Circuit assembly
Jumper Wires Several Connections

51.4 Circuit Diagram

Circuit diagram showing ESP32 DevKit connected to four LEDs through 220 ohm resistors: red LED on GPIO 2 for errors, green LED on GPIO 4 for success, yellow LED on GPIO 5 for transmission, and blue LED on GPIO 18 for packet received, all connected to common ground
Figure 51.1: Circuit diagram showing ESP32 connections to four LED indicators for packet state visualization

51.5 Packet Overhead and Efficiency

Before diving into the code, consider how packet structure affects transmission efficiency. For a packet with a 4-byte header, a variable-length payload, and a 2-byte checksum, the overhead ratio depends on how much payload you send relative to the fixed header and checksum bytes.

Try It: Packet Overhead Calculator

51.6 Optional ESP32 Implementation

Use the browser activity as the main lab. If you build the optional ESP32 version, implement the same behaviour in small pieces rather than pasting a long program at once.

ESP32 piece What to implement How to verify it works
Packet fields Version, type, length, sequence, payload, checksum Serial output shows each field clearly
LED state machine Yellow for transmit, blue for receive, green for valid, red for error LEDs change state during each demo cycle
Checksum function Recalculate a 16-bit checksum over header and payload bytes Corrupted payloads are rejected
Demo cycle Send valid data, sensor data, corrupted data, ping, and ACK packets Each cycle produces the expected LED pattern

51.7 Step-by-Step Instructions

51.7.1 Step 1: Set Up the Circuit

  1. Open your preferred ESP32 development environment
  2. Add an ESP32 DevKit to your workspace or breadboard
  3. Add 4 LEDs (red, green, yellow, blue) to the breadboard
  4. Add 4 x 220 ohm resistors for current limiting
  5. Connect each LED through its resistor to the specified GPIO pins:
    • Red LED: GPIO 2
    • Green LED: GPIO 4
    • Yellow LED: GPIO 5
    • Blue LED: GPIO 18
  6. Connect all LED cathodes (short legs) to GND

51.7.2 Step 2: Upload the Code

  1. Start from the behaviour map in the optional ESP32 section.
  2. Implement one piece at a time: packet fields, LED state changes, checksum calculation, then demo cycles.
  3. Compile after each piece so syntax errors are isolated.
  4. Run the browser simulator beside your ESP32 output and compare the packet size, checksum result, and success/error decision.

51.7.3 Step 3: Observe the Output

Watch the Serial Monitor for detailed packet information:

  1. Startup: All LEDs blink in sequence during self-test
  2. Transmission: Yellow LED lights during packet sending
  3. Reception: Blue LED indicates packet arrival
  4. Success: Green LED blinks 3 times for valid checksum
  5. Error: Red LED blinks 5 times for corrupted packets

51.7.4 Step 4: Understand the Packet Structure

Study the Serial Monitor output to identify:

Packet field Example value What to learn
Version 0x01 Identifies the packet format so future versions can coexist
Type DATA Tells the receiver whether this is data, ACK, NACK, or ping
Length 16 bytes Tells the receiver how many payload bytes to read
Sequence 0 Helps detect lost, duplicate, or out-of-order packets
Payload “Hello IoT World!” The application data carried by the packet
Hex view 48 65 6C 6C 6F … The same payload represented as bytes
Checksum 0xF8E2 Error-detection value recomputed by the receiver
Quick Check: Packet Header Fields

51.7.5 Step 5: Experiment with Errors

The demo automatically shows a corrupted packet in cycle 3. Observe how:

  • The checksum verification fails
  • The red LED indicates an error
  • A NACK (negative acknowledgment) would be sent in a real system

51.8 Expected Output

When running the simulation, your Serial Monitor should tell the same story as the LEDs:

Stage Serial monitor should show LED meaning
Startup LED test complete and pin role summary All LEDs blink once during self-test
Packet created Packet type, payload length, sequence number, and checksum No LED yet; the packet is being prepared
Transmitting Packet is being sent Yellow LED on
Received Packet arrived and checksum is being verified Blue LED on briefly
Success Checksum valid; packet accepted Green LED blinks
Error cycle Checksum invalid; retransmission would be requested Red LED blinks
Next cycle Wait period before repeating with a new packet type All LEDs off between cycles

51.9 Challenge Exercises

Challenge 1: Add Packet Acknowledgment

Modify the code to implement a complete ACK/NACK system:

  1. After receiving a valid packet, automatically create and send an ACK packet
  2. After receiving a corrupted packet, send a NACK packet requesting retransmission
  3. Add a retry counter that gives up after 3 failed attempts

Hint: Create a new function sendAcknowledgment(bool success, uint8_t seqNum) that creates and transmits the appropriate response.

Challenge 2: Implement Sequence Number Validation

Network packets can arrive out of order. Add sequence number tracking:

  1. Keep track of the last received sequence number
  2. Detect and report out-of-order packets
  3. Detect and report duplicate packets
  4. Add a purple LED (GPIO 19) that blinks for sequence errors

Hint: Store lastReceivedSequence as a global variable and compare incoming packets against it.

Challenge 3: Create a Two-ESP32 Network

For advanced learners with two ESP32 boards:

  1. Connect two ESP32s via serial (TX1-RX2, RX1-TX2)
  2. One ESP32 acts as sender, one as receiver
  3. Implement actual packet transmission over the serial line
  4. Add a button to trigger manual packet sending
  5. Display received messages on an OLED screen

Hint: Use Serial2.begin(9600, SERIAL_8N1, RX_PIN, TX_PIN) for the second serial port.

51.10 Checksum Overhead Trade-offs

In resource-constrained IoT systems, every byte counts. Adding error detection increases packet size but prevents silent data corruption. The following worked example quantifies this trade-off.

Scenario: An industrial IoT sensor transmits 10-byte temperature readings every second over an IEEE 802.15.4 wireless link (250 kbps) with a 1% packet error rate.

Given:

  • Payload: 10 bytes per packet
  • Frequency: 1 packet/second = 86,400 packets/day
  • Error rate: 1% (864 corrupted packets/day)
  • Options: No checksum vs 2-byte checksum vs 4-byte CRC32
  • Header without checksum: 4 bytes (version, type, length, sequence)

Analysis:

Option Overhead Bytes Total Bytes Overhead % Errors Detected Undetected Errors
No checksum 4 14 28.6% 0 864/day
2-byte checksum 6 16 37.5% ~863/day ~1/day
4-byte CRC32 8 18 44.4% ~864/day ~0

Energy Cost (at 10 mW transmit power, 250 kbps data rate):

  • Transmission time per byte: 8 bits / 250,000 bps = 0.032 ms/byte
  • No checksum: 14 bytes x 0.032 ms = 0.448 ms at 10 mW = 0.00124 uWh per packet
  • With 2-byte checksum: 16 bytes x 0.032 ms = 0.512 ms at 10 mW = 0.00142 uWh (+14.3%)
  • With CRC32: 18 bytes x 0.032 ms = 0.576 ms at 10 mW = 0.00160 uWh (+28.6%)

Impact Over 1 Year:

  • Undetected errors (no checksum): 315,360 corrupted readings
  • Extra energy for 2-byte checksum: ~0.16 mWh/year (negligible)
  • Trade-off: Spend a fraction of a percent more battery for 99.9% error detection

Decision: A 2-byte checksum is optimal for most IoT sensors – it catches nearly all errors with minimal overhead. CRC32 is only justified for safety-critical applications (medical devices, industrial control systems) where even a single undetected error per day is unacceptable.

Try It: Checksum Strategy Comparison

51.11 Concept Relationships

How the packet networking concepts in this lab interconnect:

Concept Relates To Key Insight
Packet Header Protocol Metadata Version, type, length, and sequence fields identify the packet and enable processing
Payload Application Data The actual sensor readings, commands, or messages being transmitted
Checksum Error Detection Mathematical verification that data was not corrupted during transmission
Sequence Numbers Ordering and Loss Detection Track packets across unreliable links, detect gaps and duplicates
ACK/NACK Reliability Confirm receipt or request retransmission to ensure delivery
Protocol Overhead Efficiency Headers and checksums consume bandwidth – minimize for constrained networks
LED State Machine Visualization Physical representation of transmission, reception, success, and error states

51.12 Match the Concepts

51.13 Order the Process

Common Pitfalls

A single simulation run produces one sample from a random process. Fix: run at least 30 independent runs with different random seeds and report the mean and 95% confidence interval.

Metrics collected during the initialisation period (when routing tables are forming) skew the results. Fix: discard the first 10–20% of simulation time as a warm-up period before recording metrics.

The default free-space path loss model ignores walls, furniture, and interference. Fix: use a more realistic model (log-distance, Two-Ray Ground, or measured empirical values) and document which model was used.

51.14 Summary

This lab demonstrated essential packet networking concepts through hands-on simulation:

  • Packet Structure: Header (version, type, length, sequence) + Payload + Checksum forms a complete self-describing data unit
  • Transmission States: Visual feedback through LEDs shows the packet lifecycle from creation through verification
  • Error Detection: Checksums catch data corruption during transmission, triggering retransmission requests
  • Protocol Design: Version fields enable backward compatibility, sequence numbers detect lost packets, and ACK/NACK mechanisms enable reliable communication over unreliable links

51.15 Knowledge Check

51.16 What’s Next

Topic Chapter Description
Network Performance Network Performance Lab Measure bandwidth, latency, and jitter with ESP32 experiments
Packet Journey Game Packet Journey Game Interactive adventure tying together all networking concepts through gamified learning
TCP/IP Protocol TCP/IP Fundamentals How real TCP protocols implement packet structure, flow control, and error handling
Error Detection Error Detection Methods CRC, checksums, and forward error correction techniques compared
Protocol Overhead Transport Overhead Analysis Minimising header waste in constrained IoT networks
Routing Structures Network Topologies Fundamentals How packets route through star, mesh, and tree network structures