LoRaWAN with The Things Network (TTN)
Connecting LoRa devices to The Things Network using LoRaWAN stack on ESP32.
Key idea:
LoRaWAN adds MAC layer on top of LoRa PHY. The Things Network (TTN) provides free community LoRaWAN network server. ESP32 runs LMIC or MCCI LoRaWAN stack.
LoRaWAN Architecture
┌─────────────┐ LoRaWAN ┌─────────────┐ MQTT/HTTP ┌─────────────┐
│ End Device │◄────────────────►│ Gateway │◄─────────────────►│ Network Svr │
│ (ESP32) │ (SF7-12, │ (Packet │ (UDP/TCP, │ (TTN) │
│ │ 125/250/500kHz)│ Forwarder)│ TLS) │ │
└─────────────┘ └─────────────┘ └─────────────┘
│
▼
┌─────────────────┐
│ Application Svr │
│ (Your App) │
└─────────────────┘
Key LoRaWAN Concepts
| Concept | Description |
|---|---|
| DevEUI | 64-bit globally unique device ID (IEEE EUI-64) |
| AppEUI | 64-bit application ID (JoinEUI in v1.1) |
| AppKey | 128-bit root key for OTAA join |
| DevAddr | 32-bit network address (assigned after join) |
| NwkSKey | Network session key (integrity) |
| AppSKey | Application session key (encryption) |
| FCnt | Frame counter (replay protection) |
| DR | Data Rate (SF + BW combination) |
| ADR | Adaptive Data Rate (server controls DR) |
OTAA vs ABP Activation
| Method | Pros | Cons |
|---|---|---|
| OTAA (Over-The-Air Activation) | Secure, session keys derived, supports roaming | Requires join procedure, gateway coverage |
| ABP (Activation By Personalization) | Immediate, no join | Pre-provisioned keys, no roaming, less secure |
TTN Console Setup
- Create Application: Console → Applications → Add Application
- Register Device: Devices → Register Device
- Device ID:
my-esp32-001 - DevEUI: Auto-generate or enter
- AppKey: Auto-generate
- Device ID:
- Get Credentials: Device → Overview → Copy DevEUI, AppEUI, AppKey
MCCI LoRaWAN Library (LMIC fork)
// CMakeLists.txt for main component
idf_component_register(
SRCS "main.c" "lorawan.c"
INCLUDE_DIRS "."
REQUIRES mcci-lmic
)
// In component.mk or idf_component.yml for MCCI LMIC
dependencies:
mcci-lmic: ">=4.0.0"LoRaWAN Configuration (lorawan_config.h)
#ifndef LORAWAN_CONFIG_H
#define LORAWAN_CONFIG_H
#include <stdint.h>
// TTN Credentials (from TTN Console)
// Format: LSB first for DevEUI/AppEUI, MSB first for AppKey
static const u1_t PROGMEM DEVEUI[8] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01 };
static const u1_t PROGMEM APPEUI[8] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
static const u1_t PROGMEM APPKEY[16] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
// Pin mapping for RFM95
const lmic_pinmap lmic_pins = {
.nss = 18,
.rxtx = LMIC_UNUSED_PIN,
.rst = 14,
.dio = {26, 25, LMIC_UNUSED_PIN}, // DIO0, DIO1, DIO2
.rxtx_rx_active = 0,
.rssi_cal = 8,
.spi_freq = 8000000,
};
// Region: US915, EU868, AS923, AU915, etc.
#define LMIC_REGION_US915
// #define LMIC_REGION_EU868
// Sub-band for US915 (TTN uses sub-band 2: channels 8-15)
// #define LMIC_US915_SB2
#endifMain Application (main.c)
#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_log.h"
#include "esp_system.h"
#include "nvs_flash.h"
#include "lmic.h"
#include "hal/hal.h"
#include "lorawan_config.h"
static const char *TAG = "lorawan";
static osjob_t send_job;
static uint8_t tx_buffer[64];
static bool joined = false;
// Sensor data
typedef struct {
float temperature;
float humidity;
float pressure;
int16_t rssi;
int8_t snr;
} sensor_data_t;
static sensor_data_t g_sensor_data;
// Callback: LMIC event handler
void onEvent(ev_t ev) {
switch (ev) {
case EV_SCAN_TIMEOUT:
ESP_LOGI(TAG, "EV_SCAN_TIMEOUT");
break;
case EV_BEACON_FOUND:
ESP_LOGI(TAG, "EV_BEACON_FOUND");
break;
case EV_BEACON_MISSED:
ESP_LOGI(TAG, "EV_BEACON_MISSED");
break;
case EV_BEACON_TRACKED:
ESP_LOGI(TAG, "EV_BEACON_TRACKED");
break;
case EV_JOINING:
ESP_LOGI(TAG, "EV_JOINING");
break;
case EV_JOINED:
ESP_LOGI(TAG, "EV_JOINED - Network joined!");
joined = true;
// Disable link check validation
LMIC_setLinkCheckMode(0);
// Set data rate (DR) and tx power
#ifdef LMIC_REGION_US915
LMIC_setDrTxpow(DR_SF7, 14); // DR3 = SF7BW125, 14 dBm
#else
LMIC_setDrTxpow(DR_SF7, 14);
#endif
break;
case EV_RFU1:
ESP_LOGI(TAG, "EV_RFU1");
break;
case EV_JOIN_FAILED:
ESP_LOGE(TAG, "EV_JOIN_FAILED");
break;
case EV_REJOIN_FAILED:
ESP_LOGE(TAG, "EV_REJOIN_FAILED");
break;
case EV_TXCOMPLETE:
ESP_LOGI(TAG, "EV_TXCOMPLETE (includes RX windows)");
if (LMIC.txrxFlags & TXRX_ACK) {
ESP_LOGI(TAG, "Received ACK");
}
if (LMIC.dataLen) {
ESP_LOGI(TAG, "Received %d bytes downlink", LMIC.dataLen);
// Process downlink
}
// Schedule next transmission
os_setTimedCallback(&send_job, os_getTime() + sec2osticks(300), do_send);
break;
case EV_LOST_TSYNC:
ESP_LOGI(TAG, "EV_LOST_TSYNC");
break;
case EV_RESET:
ESP_LOGI(TAG, "EV_RESET");
break;
case EV_RXCOMPLETE:
ESP_LOGI(TAG, "EV_RXCOMPLETE");
break;
case EV_LINK_DEAD:
ESP_LOGE(TAG, "EV_LINK_DEAD");
joined = false;
break;
case EV_LINK_ALIVE:
ESP_LOGI(TAG, "EV_LINK_ALIVE");
break;
default:
ESP_LOGI(TAG, "Unknown event: %d", ev);
break;
}
}
// Prepare and send uplink
void do_send(osjob_t *j) {
if (!joined) {
ESP_LOGW(TAG, "Not joined, retrying join...");
LMIC_startJoining();
return;
}
// Check if previous TX is done
if (LMIC.opmode & OP_TXRXPEND) {
ESP_LOGW(TAG, "TX pending, skipping");
return;
}
// Read sensors
read_sensors(&g_sensor_data);
// Encode payload (Cayenne LPP format)
int len = encode_cayenne_lpp(tx_buffer, sizeof(tx_buffer), &g_sensor_data);
ESP_LOGI(TAG, "Sending %d bytes uplink", len);
// Send uplink (port 1, unconfirmed)
LMIC_setTxData2(1, tx_buffer, len, 0);
}
// Cayenne Low Power Payload encoding
int encode_cayenne_lpp(uint8_t *buffer, int max_len, sensor_data_t *data) {
int idx = 0;
// Temperature (channel 1, type 0x67 = 0.1°C)
if (idx + 3 <= max_len) {
buffer[idx++] = 1; // Channel
buffer[idx++] = 0x67; // Type: Temperature
int16_t temp = (int16_t)(data->temperature * 10);
buffer[idx++] = (temp >> 8) & 0xFF;
buffer[idx++] = temp & 0xFF;
}
// Humidity (channel 2, type 0x68 = 0.5% RH)
if (idx + 3 <= max_len) {
buffer[idx++] = 2;
buffer[idx++] = 0x68;
uint16_t hum = (uint16_t)(data->humidity * 2);
buffer[idx++] = (hum >> 8) & 0xFF;
buffer[idx++] = hum & 0xFF;
}
// Pressure (channel 3, type 0x73 = 0.1 hPa)
if (idx + 4 <= max_len) {
buffer[idx++] = 3;
buffer[idx++] = 0x73;
uint32_t press = (uint32_t)(data->pressure * 10);
buffer[idx++] = (press >> 16) & 0xFF;
buffer[idx++] = (press >> 8) & 0xFF;
buffer[idx++] = press & 0xFF;
}
// RSSI (channel 4, type 0x00 = custom)
if (idx + 3 <= max_len) {
buffer[idx++] = 4;
buffer[idx++] = 0x00; // Generic sensor
buffer[idx++] = (data->rssi >> 8) & 0xFF;
buffer[idx++] = data->rssi & 0xFF;
}
// SNR (channel 5, type 0x00 = custom)
if (idx + 3 <= max_len) {
buffer[idx++] = 5;
buffer[idx++] = 0x00;
buffer[idx++] = 0x00;
buffer[idx++] = data->snr & 0xFF;
}
return idx;
}
void read_sensors(sensor_data_t *data) {
// Read from BME280, etc.
data->temperature = 25.0;
data->humidity = 60.0;
data->pressure = 1013.25;
data->rssi = -100;
data->snr = 10;
}
void app_main(void) {
// Initialize NVS
esp_err_t err = nvs_flash_init();
if (err == ESP_ERR_NVS_NO_FREE_PAGES || err == ESP_ERR_NVS_NEW_VERSION_FOUND) {
ESP_ERROR_CHECK(nvs_flash_erase());
err = nvs_flash_init();
}
ESP_ERROR_CHECK(err);
// Initialize LMIC
os_init();
LMIC_reset();
// Set static session parameters (for ABP)
// LMIC_setSession(0x1, DEVADDR, NWKSKEY, APPSKEY);
// Or start OTAA join
LMIC_startJoining();
// Set up callbacks
// LMIC event handler is called from LMIC context
// Schedule first send
os_setTimedCallback(&send_job, os_getTime() + sec2osticks(10), do_send);
// LMIC runloop
while (1) {
os_runloop_once();
}
}TTN Downlink Handling
// In onEvent EV_TXCOMPLETE
if (LMIC.dataLen) {
uint8_t port = LMIC.frame[LMIC.dataBeg - 1];
uint8_t *payload = &LMIC.frame[LMIC.dataBeg];
int len = LMIC.dataLen;
ESP_LOGI(TAG, "Downlink on port %d, %d bytes", port, len);
switch (port) {
case 1: // Configuration commands
if (len >= 2 && payload[0] == 0x01) { // Set interval
uint16_t interval = (payload[1] << 8) | payload[2];
ESP_LOGI(TAG, "Set interval to %d seconds", interval);
// Update send interval
}
break;
case 2: // Firmware update trigger
if (payload[0] == 0xFF) {
ESP_LOGI(TAG, "OTA update requested");
// Trigger OTA
}
break;
}
}US915 Channel Configuration (TTN)
// TTN US915 uses sub-band 2 (channels 8-15, 64-71)
void setup_us915_channels(void) {
// Disable all channels
for (int i = 0; i < 72; i++) {
LMIC_disableChannel(i);
}
// Enable sub-band 2 (channels 8-15 + 64-71)
for (int i = 8; i <= 15; i++) {
LMIC_enableChannel(i);
}
for (int i = 64; i <= 71; i++) {
LMIC_enableChannel(i);
}
// Set DR to SF7BW125 (DR3) for join
LMIC_setDrTxpow(DR_SF7, 14);
}Key Takeaways
- LoRaWAN: MAC layer on LoRa PHY with encryption, addressing, ADR
- TTN: Free community network server (EU/US/AS/AU)
- OTAA: Secure join with DevEUI/AppEUI/AppKey
- MCCI LMIC: Mature LoRaWAN stack for ESP32
- Cayenne LPP: Standard payload encoding for sensors
- US915: TTN uses sub-band 2 (channels 8-15, 64-71)
Resources
- The Things Network: https://www.thethingsnetwork.org/
- TTN Console: https://console.thethingsnetwork.org/
- MCCI LMIC Library: https://github.com/mcci-catena/arduino-lmic
- LoRaWAN Specification: https://lora-alliance.org/resource-hub/lorawan-specification-v1-0-4/
- Cayenne LPP: https://mydevices.com/cayenne/docs/lora/
Tech Stack
- ESP32, RFM95/SX127x, MCCI LMIC, LoRaWAN 1.0.4, TTN
Difficulty Note
Fast-track: 2-3 weeks · Deep-dive: 4-6 weeks