LoRa and LoRaWAN
Spreading factor, link budget, device classes and ADR.
Kilometres on a coin cell
LoRa is a radio modulation, designed by Semtech, that reaches several kilometres (over 10 km in open country) with milliwatts of transmit power, at the cost of very low data rates. LoRaWAN is the network protocol built on top of it by the LoRa Alliance. They are often confused:
| LoRa | LoRaWAN | |
|---|---|---|
| What | Physical layer: chirp spread spectrum modulation | MAC and network architecture |
| Defines | How bits become radio signals | Addressing, security, device classes, gateways and network servers |
| Can be used alone | Yes, for point-to-point links | Needs LoRa (or FSK) underneath |
LoRa operates in unlicensed sub-GHz bands: 863 to 870 MHz in Europe, 902 to 928 MHz in North America, others elsewhere, each with its own regulations.
How LoRa reaches so far
LoRa uses chirp spread spectrum: each symbol is a frequency sweep (a chirp) across the channel bandwidth, and data is encoded in where the sweep starts. Spreading the signal makes it decodable below the noise floor (down to about −20 dB SNR) and robust against interference and Doppler shift.
Three parameters set the trade-off between range, speed and airtime:
| Parameter | Values | Effect |
|---|---|---|
| Spreading factor (SF) | SF7 to SF12 | Each step up doubles the symbol time: about 2.5 dB more sensitivity (range), half the data rate, double the airtime and energy |
| Bandwidth (BW) | 125, 250, 500 kHz | Wider: faster, less sensitive |
| Coding rate (CR) | 4/5 to 4/8 | More forward error correction, more airtime |
Bit rate ≈ SF × BW / 2^SF × CR. At 125 kHz, SF7 gives about 5.5 kbit/s, SF12 about 250 bit/s.
#include <stdio.h>
#include <math.h>
/* LoRa time on air, from the Semtech SX127x datasheet formula (explicit header, CRC on). */
static double airtime_ms(int sf, double bw_khz, int payload, int cr /* 1..4 for 4/5..4/8 */) {
double t_sym = pow(2, sf) / bw_khz; /* ms */
int de = (t_sym > 16.0) ? 1 : 0; /* low data rate optimisation */
double extra = ceil((8.0 * payload - 4 * sf + 28 + 16) / (4.0 * (sf - 2 * de))) * (cr + 4);
double n = 8 + (extra > 0 ? extra : 0);
return (8 + 4.25) * t_sym + n * t_sym; /* 8-symbol preamble */
}
int main(void) {
for (int sf = 7; sf <= 12; sf++)
printf("SF%-2d, 125 kHz, 20-byte payload: %7.1f ms on air\n", sf, airtime_ms(sf, 125.0, 20, 1));
return 0;
}
The jump from SF7 to SF12 multiplies airtime about 20 times, and with it energy, channel occupancy and duty-cycle consumption.
Duty cycle and airtime limits
Unlicensed bands limit how much each device may transmit. In Europe, most LoRaWAN sub-bands allow 1% duty cycle: a transmission of 1 s means 99 s of silence on that sub-band. US rules limit dwell time per channel to 400 ms instead. Public networks add fair-use limits (for example 30 s of uplink airtime per device per day on The Things Network). These rules, more than the radio, decide how often a device can send.
LoRaWAN architecture
end devices ~~radio~~> gateways --IP--> network server --> application server
(sensors) (many) (dedupe, ADR, MAC) (your backend)
- End devices transmit; any gateway in range receives (there is no association with a particular gateway).
- Gateways forward every packet they hear to the network server over IP. Several gateways may receive the same packet, which improves reliability.
- The network server removes duplicates, manages the network (ADR, MAC commands), and chooses a gateway for downlinks.
- The application server receives decrypted application data.
Networks can be public (The Things Network, Helium, operator networks) or private (your own gateways and a network server such as ChirpStack).
Device classes
| Class | Downlink reception | Power | Use |
|---|---|---|---|
| A (all devices) | Only in two short receive windows (RX1, RX2) after each uplink | Lowest | Battery sensors |
| B | Plus scheduled ping slots synchronised to gateway beacons | Medium | Battery devices needing occasional downlink without uplinking |
| C | Listening continuously except while transmitting | Highest | Mains-powered actuators, street lights |
A Class A device sending once an hour can only receive commands once an hour; design the application around that.
Joining and security
Each device needs keys. Two activation methods:
- OTAA (over-the-air activation): the device has a DevEUI, JoinEUI and root key AppKey; it sends a join request, and session keys are derived per session. Recommended.
- ABP (activation by personalisation): session keys and device address are programmed in. Simpler, but keys never change and frame counters must survive resets; avoid for production.
Every message is encrypted end to end with the AppSKey (the network cannot read the payload) and integrity-protected with the NwkSKey (the network checks it). Frame counters prevent replay; a device that resets its counter will have uplinks dropped as replays unless counters are stored in non-volatile memory (or the device rejoins).
Adaptive data rate (ADR)
The network server watches each device's signal quality across gateways and tells it, via MAC commands, which spreading factor and transmit power to use. A device near a gateway moves to SF7 and low power (short airtime, long battery life); a distant one stays at a higher SF. ADR suits static devices; mobile devices should disable it and choose conservatively, because the conditions change faster than ADR adapts.
Practical design notes
- Payloads should be tiny: bytes, not JSON. Pack readings into bits (a temperature as a signed 16-bit value in centi-degrees), and decode on the server.
- Confirmed uplinks (acknowledged) cost a downlink, which gateways must transmit and which counts against their duty cycle too; use them sparingly.
- Firmware updates over LoRaWAN are possible (FUOTA with multicast and fragmentation) but slow; many products use a different path.
- Antenna and placement matter more than anything: a gateway on a rooftop versus a basement can be the difference between 10 km and 500 m.
Pitfall: Testing a LoRaWAN device right next to a gateway can fail because the receiver is saturated. Keep at least a few metres between device and gateway antennas on the bench.
Interview question: Why can a LoRaWAN Class A device not receive a command at any time?
Answer: To save power, a Class A device only listens in two short receive windows that open one and two seconds (configurable) after each of its own uplinks; the rest of the time its radio is off. The network server queues downlinks and sends them in those windows, so commands are delivered only when the device next transmits. If faster downlink is needed, use Class B (scheduled ping slots) or Class C (continuous listening, for mains-powered devices).
Interview question: How would you design the payload for a LoRaWAN soil sensor reporting temperature, moisture and battery?
Answer: Use a compact fixed binary layout rather than text: for example temperature as a signed 16-bit value in hundredths of a degree, moisture as an unsigned byte in half-percent steps, and battery as a byte in 10 mV steps above a base voltage, giving about 4 bytes plus a version or flags byte. Use the LoRaWAN port number to identify the message type, and decode on the network or application server. Small payloads reduce airtime, energy and duty-cycle use, and allow the use of lower data rates for range.
Build it: stay inside the airtime rules
This is step 5 of the module project, the shipping-container tracker tag. Inland depots have no Wi-Fi worth the name, so the tag sends its position over LoRaWAN to the operator's gateways. European rules allow each device only 1% of the time on air in its sub-band, and the network adds a fair-use budget of 30 s of uplink a day. A tag that ignores them gets the operator's licence questioned and itself blocked; the radio will not stop you.
Lab: Time on air in integers, and a duty-cycle limiter
lora_airtime_us(sf, len)returns the time on air in microseconds at 125 kHz bandwidth, coding rate 4/5, explicit header, CRC on, an 8-symbol preamble, for spreading factor 7 to 12. In integers only:- one symbol lasts
2^SF × 8µs at 125 kHz; - the preamble lasts 12.25 symbols (
49 × Tsym / 4); - the payload takes
8 + max(ceil((8 × len − 4 × SF + 44) / (4 × (SF − 2 × DE))) × 5, 0)symbols, where DE (low data rate optimisation) is 1 for SF11 and SF12 and 0 otherwise. Mind themax: the fraction can be negative. dc_try(dc, now_ms, airtime_us)is called before each uplink and returns:TX_WAITwhen the 1% duty cycle forbids sending yet: after a transmission oftms, the next may start no earlier than100 × tms after the last one started;TX_BUDGETwhen this uplink would take the day's total overDAY_BUDGET_MS(a day isnow_ms / 86400000, and a new day starts a new budget);- otherwise
TX_OK, after recording the transmission.
Count airtime in whole milliseconds, rounded up.
Going deeper
Interview question: How would you design a farm soil-moisture network that runs for years on batteries?
Answer: Sensors sleep and send a few bytes a few times a day over LoRaWAN, with the spreading factor set by adaptive data rate so close nodes use short airtime. Gateways cover the farm, the network server deduplicates and forwards, and nodes confirm only important messages to save energy and respect duty-cycle limits. Budget the battery from the airtime of each message.
Interview question: Why must a LoRaWAN device using ABP store its frame counters in non-volatile memory?
Answer: The network rejects any uplink whose frame counter is not higher than the last one received, as protection against replay attacks. With ABP, the session keys never change, so if the device resets and restarts its counter from zero, all its messages are rejected until the counter passes the old value. Storing the counter in non-volatile memory (or using OTAA, which starts a new session on each join) avoids this.
Interview question: What is the difference between confirmed and unconfirmed uplinks?
Answer: An unconfirmed uplink is sent once without acknowledgement; a confirmed uplink asks the network to send an acknowledgement in a receive window, and the device retries if none arrives. Confirmed messages use gateway downlink capacity, which is limited by duty-cycle rules and shared by all devices, so they should be reserved for important messages.
Explain it: In your own words, explain how adaptive data rate helps both the device and the network.
Answer: The network server sees each device's signal quality at the gateways and, for static devices, tells them through MAC commands which spreading factor and transmit power to use. A device with a strong signal is moved to a low spreading factor and lower power, so each message takes much less airtime and energy, extending its battery and using less of the shared channel. Devices far away keep higher spreading factors so they are still heard. The whole network carries more traffic with fewer collisions.