14 LoRaWAN Simulation Lab
14.1 Learning Objectives
By completing this lab, you will be able to:
- Analyze LoRaWAN packet structure: Identify and explain the role of DevAddr, FCnt (frame counter), FPort, and encrypted payload fields in a captured uplink frame
- Implement uplink/downlink communication: Construct Class A transmit-receive cycles with correctly timed RX1 and RX2 windows
- Differentiate spreading factor trade-offs: Measure how SF7-SF12 affects airtime, simulated range, throughput, and duty cycle consumption
- Enforce duty cycle compliance: Calculate and track cumulative airtime against the 1% EU868 regulatory limit per sub-band
- Evaluate ADR convergence: Predict and verify how the network automatically adjusts spreading factors based on link margin over successive uplink cycles
For Beginners: LoRaWAN Simulation Lab
This lab lets you experiment with LoRaWAN networks in a simulator – deploying gateways, placing sensors, adjusting spreading factors, and observing how data flows through the network. You can test different configurations without needing physical hardware, making it a great way to learn LoRaWAN concepts hands-on.
Sensor Squad: Simulating LoRaWAN on ESP32
“Real LoRaWAN radios cost money, but we can learn everything with a free simulator!” said Max the Microcontroller, opening Wokwi in a browser. “This ESP32 simulation mimics the entire LoRaWAN protocol: packet structure with encrypted payloads, Class A receive windows, spreading factor effects, duty cycle tracking, and even ADR!”
Sammy the Sensor was excited. “What will I see?” Max explained, “You will watch packets being built byte by byte – DevAddr, frame counter, port, and encrypted payload. Then after transmitting, two receive windows open up at exactly 1 second and 2 seconds later. If the network has a downlink, it arrives in one of those windows.”
“The coolest part is watching spreading factor effects,” said Lila the LED. “When you switch from SF7 to SF12, the airtime goes from 61 milliseconds to over 1.5 seconds. You can actually see the duty cycle counter climbing much faster at higher spreading factors. It makes the trade-off between range and efficiency totally concrete.”
Bella the Battery encouraged experimentation. “Try enabling ADR and watch it converge. After about 20 successful transmissions, the network server starts lowering your SF from 12 down toward 7. Your battery life projection improves with each adjustment. Then try moving the simulated sensor farther away and watch ADR increase the SF back up to maintain the link.”
14.2 Why Simulate LoRaWAN?
Real LoRaWAN requires specialized hardware (SX1276/SX1262 radio modules) and operates in unlicensed ISM bands (EU868/US915) with regulatory duty cycle constraints. This simulation lets you:
- Learn protocol mechanics without hardware investment
- Visualize packet flow that would be invisible with real radios
- Experiment with ADR in seconds instead of hours
- Test duty cycle scenarios without regulatory concerns
The simulation accurately models packet structure, timing behaviors, and protocol state machines - the same concepts you will apply with real LoRaWAN hardware.
14.3 LoRaWAN Concepts Demonstrated
| Concept | Real LoRaWAN | This Simulation |
|---|---|---|
| Physical Layer | LoRa CSS modulation | ESP-NOW 2.4 GHz |
| Packet Format | PHYPayload with MHDR, MACPayload, MIC | Identical structure |
| Spreading Factor | SF7-SF12 radio parameter | Simulated airtime delays |
| Duty Cycle | 1% TX time per hour | Tracked and enforced |
| ADR | Network server algorithm | Simplified SNR-based |
| Device Classes | Class A/B/C | Class A implemented |
| Security | AES-128 encryption | Simulated (visible for learning) |
14.4 Lab Architecture
The simulation creates a LoRaWAN network with three ESP32 devices:
14.5 Embedded Wokwi Simulator
How to Use This Simulator
- Click the green Play button to start the simulation
- Watch the Serial Monitor for detailed LoRaWAN packet logs
- Copy the code from the repository to run the full demonstration
- Modify spreading factors and observe the airtime changes
- Trigger downlinks by pressing the boot button on end devices
14.6 Lab Challenges
14.6.1 Challenge 1: Implement Confirmed Uplinks
Modify the end device to send confirmed uplinks and handle ACK responses:
- Change
MTypefrom 2 (Unconfirmed) to 4 (Confirmed) in uplink frames - Implement ACK timeout and retransmission logic
- Track confirmed vs. unconfirmed delivery rates
- Observe how confirmed uplinks affect duty cycle budget
14.6.2 Challenge 2: Add Class B Beacon Simulation
Extend the simulation to support Class B scheduled receive windows:
- Gateway broadcasts a beacon every 128 seconds
- End device synchronizes to beacon and opens ping slots
- Implement ping slot scheduling based on DevAddr hash
- Compare downlink latency between Class A and Class B
14.6.3 Challenge 3: Implement Join Procedure (OTAA)
Add the LoRaWAN join procedure:
- Create JoinRequest message with DevEUI and JoinEUI (called AppEUI in LoRaWAN 1.0)
- Gateway forwards JoinRequest to the network server, which responds with JoinAccept containing DevAddr and network parameters
- Derive AppSKey and NwkSKey from the root AppKey using nonces exchanged in the join procedure
- Transition from join state to data transmission state
14.6.4 Challenge 4: Multi-Gateway Reception
Simulate multiple gateways receiving the same uplink:
- Add a second gateway node
- Both gateways forward uplinks to the “network server”
- Implement deduplication logic (keep best RSSI)
- Demonstrate how multi-gateway improves reliability
14.7 Key Concepts Learned
14.7.1 Concept: DevAddr and Frame Counters
DevAddr (Device Address) is a 4-byte network-assigned identifier: - Assigned during join (OTAA) or pre-configured (ABP) - Used for routing at the network server - Format: 0x26XXXXXX for private networks
Frame Counters (FCnt) prevent replay attacks: - FCntUp: Incremented by device on each uplink - FCntDown: Incremented by network on each downlink - Network rejects packets with out-of-sequence counters
14.7.2 Concept: Spreading Factor Trade-offs
| SF | Airtime (20 bytes) | Range | Sensitivity | Battery Impact |
|---|---|---|---|---|
| SF7 | 50 ms | ~2 km | -123 dBm | Lowest (1x) |
| SF8 | 100 ms | ~4 km | -126 dBm | 2x |
| SF9 | 200 ms | ~6 km | -129 dBm | 4x |
| SF10 | 400 ms | ~8 km | -132 dBm | 8x |
| SF11 | 800 ms | ~11 km | -134.5 dBm | 16x |
| SF12 | 1600 ms | ~15 km | -137 dBm | 32x |
14.7.3 Concept: Duty Cycle Regulations
EU868 Regulations:
- Sub-band g (868.0-868.6 MHz): 1% duty cycle = 36 seconds/hour
- Sub-band g1 (868.7-869.2 MHz): 0.1% = 3.6 seconds/hour
- Sub-band g3 (869.4-869.65 MHz): 10% = 360 seconds/hour (used for downlinks)
US915 Regulations: No duty cycle limit, but: - 400ms dwell time per channel - Frequency hopping required (>50 channels) - Fair Access Policy recommends 30 seconds/day
14.7.4 Concept: Adaptive Data Rate (ADR)
How ADR Works:
- Network server collects SNR/RSSI from last 20 uplinks
- Calculates link margin above sensitivity threshold
- If margin > 10 dB, recommends lower SF (faster, less power)
- Sends LinkADRReq MAC command in downlink
- Device acknowledges and applies new SF
Worked Example: Calculating ADR Convergence Time
Scenario: Your simulated LoRaWAN device starts at SF12 with poor RSSI (-120 dBm). How long until ADR optimizes it to SF7?
ADR Algorithm Requirements:
- Network server needs 20 consecutive successful uplinks to evaluate link quality
- Margin target: 10-15 dB above sensitivity threshold
- SF adjustment: One step per ADR cycle (SF12 → SF11 → SF10 → … → SF7)
Calculation:
- Initial State (SF12):
- Sensitivity: -137 dBm
- Your RSSI: -120 dBm
- Link margin: -120 - (-137) = 17 dB (excellent!)
- Airtime: 1.48 seconds per message
- ADR Cycle 1 (after 20 messages at SF12):
- Margin > 15 dB → Network recommends SF11
- Device acknowledges and switches to SF11
- New airtime: 0.74 seconds
- ADR Cycle 2 (after 20 messages at SF11):
- Sensitivity: -134.5 dBm
- Margin: -120 - (-134.5) = 14.5 dB → Still good
- Network recommends SF10
- New airtime: 0.37 seconds
- Cycles 3-5: Continue stepping down (SF10 → SF9 → SF8 → SF7)
Time Calculation:
Messages per cycle: 20
Cycles needed: 5 (SF12 → SF7 = 5 steps)
Total messages: 100
At 10-minute intervals:
100 messages × 10 min = 1,000 minutes = 16.7 hours
At 5-minute intervals:
100 messages × 5 min = 500 minutes = 8.3 hours
Real-World Impact:
- Battery life improvement: SF12 uses 32× more energy than SF7
- Network capacity increase: SF7 frees airtime for 8× more devices
- Reliability: ADR automatically reacts if conditions worsen (moves back to higher SF)
Key Insight: ADR converges faster with frequent transmissions. A device sending every minute reaches optimal SF in ~100 minutes, while hourly transmissions take 4+ days. For battery-powered sensors, this trade-off between convergence speed and energy consumption must be carefully balanced.
Putting Numbers to It
ADR requires 20 consecutive successful uplinks per SF adjustment. For a 5-step SF optimization (SF12→SF7):
\[\text{Total messages needed} = 20 \times 5 = 100 \text{ messages}\]
At different transmission intervals:
\[\text{Convergence time} = 100 \times \text{interval}\]
Worked example with 10-minute intervals:
- Total time: \(100 \times 10 \text{ min} = 1,000 \text{ minutes} \approx 16.7 \text{ hours}\)
- Energy at SF12 (first 20 msgs): \(20 \times 1.48 \text{ s} \times 120 \text{ mA} = 3{,}552 \text{ mAs} \approx 0.99 \text{ mAh}\)
- Energy at SF7 (final 20 msgs): \(20 \times 0.061 \text{ s} \times 120 \text{ mA} = 146.4 \text{ mAs} \approx 0.041 \text{ mAh}\)
- Total convergence energy: ~2.2 mAh (sum across all SF steps, including RX windows)
Faster transmission speeds up convergence but uses more total energy during the optimization phase.
14.8 Concept Relationships
| Concept | Builds On | Enables | Contrasts With |
|---|---|---|---|
| LoRaWAN Packet Structure | PHY/MAC layering, frame formats | Device-gateway communication, security | Wi-Fi 802.11 frames (ack every packet), Zigbee (cluster-based addressing) |
| Spreading Factor Simulation | LoRa CSS modulation theory, link budget | Range vs. airtime trade-off visualization | FSK (fixed sensitivity), OFDM (subcarrier allocation) |
| Duty Cycle Tracking | EU868 ETSI regulations, airtime calculation | Regulatory compliance, fair spectrum access | US915 (no duty cycle), NB-IoT (operator-managed spectrum) |
| ADR Simulation | SNR monitoring, link margin optimization | Battery life improvement, network capacity scaling | Fixed SF (manual configuration), Sigfox (no ADR) |
| Class A Receive Windows | LoRaWAN MAC timing, downlink scheduling | Bidirectional communication with low power | Class C (continuous RX), Zigbee (always-on receivers) |
| ESP-NOW Transport Layer | ESP32 radio capabilities, packet framing | LoRaWAN protocol simulation without LoRa hardware | Actual LoRa radio (SX1276/SX1262 physical layer) |
| Multi-Gateway Reception | Spatial diversity, deduplication algorithms | Coverage redundancy, reliability improvement | Single gateway (no redundancy), Cellular (handoff required) |
14.9 See Also
LoRaWAN Fundamentals:
- LoRaWAN Network Architecture - Detailed protocol architecture and component roles
- LoRaWAN Physical Layer Review - Spreading factors, modulation, and link budget analysis
- ADR Optimization - Deep dive into Adaptive Data Rate algorithms
Hands-On Practice:
- LoRaWAN Practice Exercises - Conceptual questions and calculations based on simulation insights
- LoRaWAN Deployment Review - Real-world gateway planning and troubleshooting
Related Simulations:
- MQTT Wokwi Lab - ESP32 MQTT publish/subscribe patterns
- CoAP Wokwi Lab - Constrained Application Protocol simulation
14.10 Lab Summary
| Exercise | LoRaWAN Concept | What You Learned |
|---|---|---|
| Basic transmission | Packet structure | DevAddr, FCnt, FPort, MIC fields |
| SF modification | Spreading factors | Airtime vs range trade-off |
| Duty cycle test | Regulatory compliance | EU868 1% limit enforcement |
| Multi-device | ADR algorithm | Network-optimized SF selection |
| Challenge 1 | Confirmed messages | Reliability with ACK/retry |
| Challenge 2 | Class B | Beacon-synchronized receive |
| Challenge 3 | OTAA | Secure device activation |
| Challenge 4 | Redundancy | Multi-gateway reception |
14.11 Real Hardware Next Steps
After completing this simulation lab, you are ready to work with real LoRaWAN hardware:
- Hardware: Get an ESP32 + SX1276/SX1262 module (Heltec WiFi LoRa 32, TTGO LoRa32, or separate module)
- Library: Use LMIC (LoRaWAN-in-C) or RadioLib for Arduino
- Network: Register with The Things Network (TTN) or Chirpstack
- Activation: Use OTAA (more secure) or ABP (simpler for testing)
The packet structures and concepts from this lab translate directly to real deployments - the primary difference is the physical LoRa radio layer.
14.12 Knowledge Check
Common Pitfalls
1. Assuming Simulation Results Directly Translate to Real Deployments
Simulations use simplified propagation models and ideal conditions. Real-world deployments have terrain variability, building attenuation, interference, and hardware variations not captured in simulations. Use simulations for directional planning, then validate with field testing.
2. Not Varying Simulation Parameters
Running simulations with a single configuration misses the impact of parameter variations. Always test a range of spreading factors, gateway positions, device densities, and message rates to understand deployment sensitivity to these variables.
3. Ignoring Simulation Tool Assumptions
Different simulation tools make different assumptions about path loss models, collision behavior, and ADR implementation. Understand the specific model used before interpreting results; results from different tools may not be directly comparable.
4. Using Lab Results to Justify Skipping Field Testing
Simulation and lab validation are preparation for field deployment, not replacements for it. Physical RF propagation in real environments always differs from models. Treat lab success as necessary but not sufficient for production deployment confidence.
14.13 What’s Next
| Direction | Chapter | Focus |
|---|---|---|
| Next | LoRaWAN Practice Exercises | Conceptual questions and calculations based on simulation insights |
| Deeper | LoRaWAN Architecture | Deep dive into protocol specifications and MAC layer details |
| Return to Overview | LoRaWAN Overview | Chapter index and learning path navigation |