viernes, 9 de enero de 2026

LoRa SX1262

Programación desde el IDE de Arduino

Se puede utilizar la librería RadioLib.

 

Conexiones ESP32 - SX1262

SX1262
ESP32
NSS / CS
GPIO 5
MOSI
GPIO 23
MISO
GPIO 19
SCK
GPIO 18
BUSY
GPIO 32
DIO1
GPIO 33
RESET
GPIO 14
GND
GND
VCC
3.3V 

Código TRANSMISOR (TX)
#include <RadioLib.h>
// Definición de pines
SX1262 lora = new Module(5, 33, 14, 32);
void setup() {
Serial.begin(115200);
Serial.print("Inicializando SX1262... ");
int state = lora.begin(915.0); // Cambia a 868.0 o 433.0 si es necesario
if (state == RADIOLIB_ERR_NONE) {
Serial.println("OK!");
} else {
Serial.print("Error: ");
Serial.println(state);
while (true);
}
}
void loop() {
Serial.print("Enviando paquete... ");
int state = lora.transmit("Hola desde ESP32 + SX1262");
if (state == RADIOLIB_ERR_NONE) {
Serial.println("Enviado!");
} else {
Serial.print("Error: ");
Serial.println(state);
}
delay(5000);
}
Código RECEPTOR (RX)
#include <RadioLib.h>
SX1262 lora = new Module(5, 33, 14, 32);
void setup() {
Serial.begin(115200);
Serial.print("Inicializando SX1262... ");
int state = lora.begin(915.0);
if (state == RADIOLIB_ERR_NONE) {
Serial.println("OK!");
} else {
Serial.print("Error: ");
Serial.println(state);
while (true);
}
}
void loop() {
String mensaje;
int state = lora.receive(mensaje);
if (state == RADIOLIB_ERR_NONE) {
Serial.print("Mensaje recibido: ");
Serial.println(mensaje);
}
}

Parámetros opcionales 

Después de lora.begin() puedes ajustar:

lora.setSpreadingFactor(7);
lora.setBandwidth(125.0);
lora.setCodingRate(5);
lora.setOutputPower(17);
Instalar la librería RadioLib

Desde el Arduino IDE 

  1. Abrir Arduino IDE

  2. Ir al menú:
    Sketch → Include Library → Manage Libraries…

  3. En la barra de búsqueda escribir:
    RadioLib

  4. Aparecerá:
    RadioLib – Jan Gromes

  5. Hacer clic en Install

  6. Esperar a que termine la instalación

SeeedStudio

// REV 5.4a - SX1262 Beacon Sender with TX Power Toggle // Board: ESP32-S3 with SX1262 LoRa Module // Sends "Seeed Studio" beacon every 3 seconds // Button on GPIO 21 toggles power (10 <-> 22 dBm) // LED on GPIO 48 blinks on each send #include <RadioLib.h> SX1262 radio = new Module(41, 39, 42, 40); // NSS, DIO1, RST, BUSY const char* message = "Seeed Studio"; // just change this to whatever...Beacon message you want // const int ledPin = 48; const int buttonPin = 21; int currentPower = 22; bool lastButton = HIGH; void setup() { Serial.begin(115200); delay(1000); pinMode(ledPin, OUTPUT); pinMode(buttonPin, INPUT_PULLUP); Serial.println(F("// REV 5.4a - SX1262 Beacon Sender with TX Power Toggle")); Serial.println(F("// Board: ESP32-S3 with SX1262 LoRa Module")); Serial.print("Initializing SX1262 LoRa radio... "); if (radio.begin() != RADIOLIB_ERR_NONE) { Serial.println("FAILED!"); while (true); } Serial.println("SUCCESS!"); // Apply standard LoRa settings radio.setSpreadingFactor(7); radio.setBandwidth(125.0); // ✅ correct for newer versions radio.setCodingRate(5); radio.setOutputPower(currentPower); Serial.print("TX Power set to "); Serial.print(currentPower); Serial.println(" dBm"); } void loop() { bool button = digitalRead(buttonPin); if (button == LOW && lastButton == HIGH) { // Toggle between 10 and 22 dBm currentPower = (currentPower == 22) ? 10 : 22; radio.setOutputPower(currentPower); Serial.print("TX Power changed to "); Serial.print(currentPower); Serial.println(" dBm"); delay(250); // debounce delay } lastButton = button; digitalWrite(ledPin, HIGH); radio.transmit(message); digitalWrite(ledPin, LOW); Serial.print("."); static int dotCount = 0; dotCount++; if (dotCount >= 80) { Serial.println(); dotCount = 0; } delay(3000); }

Rakwireless

I’m also trying to communicate ESP32+SX1262 with RAK3172 in LORA mode.
I’m using the Radiolib library in the ESP32:

radio.setFrequency(868.8);
radio.setBandwidth(125.0);
radio.setSpreadingFactor(7); // SF7
radio.setCodingRate(5); // CR4/5
radio.setOutputPower(10);
radio.setSyncWord(0x34);
radio.setPreambleLength(8);
radio.invertIQ(false);
radio.explicitHeader();
radio.setCRC(0);

Sparkfun

#include <RadioLib.h> // SX1276 requires the following connections: int pin_cs = 10; // Chip Select int pin_dio0 = 2; // DIO0 int pin_nrst = 9; // Reset int pin_dio1 = 3; // DIO1 int pin_rx_enable = 4; // RX Enable int pin_tx_enable = 5; // TX Enable SX1276 radio = new Module(pin_cs, pin_dio0, pin_nrst, pin_dio1); void setup() { Serial.begin(9600); // Initialize serial communication at 9600 baud rate delay(500); // Wait for Arduino to be ready to print Serial.print("[SX1276] Initializing ... "); int state = radio.begin(915.0); // Use the correct frequency for your region if (state == RADIOLIB_ERR_NONE) { Serial.println("init success!"); } else { Serial.print("failed, code "); Serial.println(state); while (true); // Halt execution if initialization fails } radio.setRfSwitchPins(pin_tx_enable, pin_rx_enable); } void loop() { Serial.println("Checking for data..."); if (radio.available()) { String receivedMessage; int state = radio.receive(receivedMessage); if (state == RADIOLIB_ERR_NONE) { Serial.print("Received message: "); Serial.println(receivedMessage); // Get and print the RSSI value int rssi = radio.getRSSI(); Serial.print("RSSI: "); Serial.println(rssi); } else { Serial.print("Receive failed, code "); Serial.println(state); } } else { Serial.println("No data available"); } delay(1000); // Adjust delay to ensure the receiver has time to process data

Arduino LORA




/*
  RadioLib SX126x Blocking Receive Example

  This example listens for LoRa transmissions using SX126x Lora modules.
  To successfully receive data, the following settings have to be the same
  on both transmitter and receiver:
  - carrier frequency
  - bandwidth
  - spreading factor
  - coding rate
  - sync word
  - preamble length

  Other modules from SX126x family can also be used.

Using blocking receive is not recommended, as it will lead
to significant amount of timeouts, inefficient use of processor
time and can some miss packets!
Instead, interrupt receive is recommended.

  For default module settings, see the wiki page
  https://github.com/jgromes/RadioLib/wiki/Default-configuration#sx126x---lora-modem

  For full API reference, see the GitHub Pages
  https://jgromes.github.io/RadioLib/
*/

// include the library
#include <RadioLib.h>

// SX1262 has the following connections:
// NSS pin:   10
// DIO1 pin:  2
// NRST pin:  3
// BUSY pin:  9
SX1262 radio = new Module(5, 14, 12, 13);

// or detect the pinout automatically using RadioBoards
// https://github.com/radiolib-org/RadioBoards
/*
#define RADIO_BOARD_AUTO
#include <RadioBoards.h>
Radio radio = new RadioModule();
*/

void setup() {
  Serial.begin(9600);

  // initialize SX1262 with default settings
  Serial.print(F("[SX1262] Initializing ... "));
  int state = radio.begin();
  if (state == RADIOLIB_ERR_NONE) {
    Serial.println(F("success!"));
  } else {
    Serial.print(F("failed, code "));
    Serial.println(state);
    while (true) { delay(10); }
  }
}

void loop() {
  Serial.print(F("[SX1262] Waiting for incoming transmission ... "));

  // you can receive data as an Arduino String
  String str;
  int state = radio.receive(str);

  // you can also receive data as byte array
  /*
    byte byteArr[8];
    int state = radio.receive(byteArr, 8);
  */

  if (state == RADIOLIB_ERR_NONE) {
    // packet was successfully received
    Serial.println(F("success!"));

    // print the data of the packet
    Serial.print(F("[SX1262] Data:\t\t"));
    Serial.println(str);

    // print the RSSI (Received Signal Strength Indicator)
    // of the last received packet
    Serial.print(F("[SX1262] RSSI:\t\t"));
    Serial.print(radio.getRSSI());
    Serial.println(F(" dBm"));

    // print the SNR (Signal-to-Noise Ratio)
    // of the last received packet
    Serial.print(F("[SX1262] SNR:\t\t"));
    Serial.print(radio.getSNR());
    Serial.println(F(" dB"));

    // print frequency error
    Serial.print(F("[SX1262] Frequency error:\t"));
    Serial.print(radio.getFrequencyError());
    Serial.println(F(" Hz"));

  } else if (state == RADIOLIB_ERR_RX_TIMEOUT) {
    // timeout occurred while waiting for a packet
    Serial.println(F("timeout!"));

  } else if (state == RADIOLIB_ERR_CRC_MISMATCH) {
    // packet was received, but is malformed
    Serial.println(F("CRC error!"));

  } else {
    // some other error occurred
    Serial.print(F("failed, code "));
    Serial.println(state);

  }
}




/*
   RadioLib SX126x Channel Activity Detection Example

   This example uses SX1262 to scan the current LoRa
   channel and detect ongoing LoRa transmissions.
   Unlike SX127x CAD, SX126x can detect any part
   of LoRa transmission, not just the preamble.

   Other modules from SX126x family can also be used.

   For default module settings, see the wiki page
   https://github.com/jgromes/RadioLib/wiki/Default-configuration#sx126x---lora-modem

   For full API reference, see the GitHub Pages
   https://jgromes.github.io/RadioLib/
*/

// include the library
#include <RadioLib.h>
#define LORA_FREQ 900.0

// SX1262 has the following connections:
// NSS pin:   10
// DIO1 pin:  2
// NRST pin:  3
// BUSY pin:  9
SX1262 radio = new Module(5, 14, 12, 13);

// or using RadioShield
// https://github.com/jgromes/RadioShield
//SX1262 radio = RadioShield.ModuleA;

// or using CubeCell
//SX1262 radio = new Module(RADIOLIB_BUILTIN_MODULE);

void setup() {
  Serial.begin(9600);

  // initialize SX1262 with default settings
  Serial.print(F("[SX1262] Initializing ... "));
  int state = radio.begin();
  if (state == RADIOLIB_ERR_NONE) {
    Serial.println(F("success!"));
  } else {
    Serial.print(F("failed, code "));
    Serial.println(state);
    while (true);
  }

  // set the function that will be called
  // when LoRa packet or timeout is detected
  radio.setDio1Action(setFlag);

  // start scanning the channel
  Serial.print(F("[SX1262] Starting scan for LoRa preamble ... "));
  state = radio.startChannelScan();
  if (state == RADIOLIB_ERR_NONE) {
    Serial.println(F("success!"));
  } else {
    Serial.print(F("failed, code "));
    Serial.println(state);
  }
}

// flag to indicate that a packet was detected or CAD timed out
volatile bool scanFlag = false;

// this function is called when a complete packet
// is received by the module
// IMPORTANT: this function MUST be 'void' type
//            and MUST NOT have any arguments!
#if defined(ESP8266) || defined(ESP32)
  ICACHE_RAM_ATTR
#endif
void setFlag(void) {
  // something happened, set the flag
  scanFlag = true;
}

void loop() {
  // check if the flag is set
  if(scanFlag) {
    // reset flag
    scanFlag = false;

    // check CAD result
    int state = radio.getChannelScanResult();

    if (state == RADIOLIB_LORA_DETECTED) {
      // LoRa packet was detected
      Serial.println(F("[SX1262] Packet detected!"));

    } else if (state == RADIOLIB_CHANNEL_FREE) {
      // channel is free
      Serial.println(F("[SX1262] Channel is free!"));

    } else {
      // some other error occurred
      Serial.print(F("[SX1262] Failed, code "));
      Serial.println(state);

    }

    // start scanning the channel again
    Serial.print(F("[SX1262] Starting scan for LoRa preamble ... "));
    state = radio.startChannelScan();
    if (state == RADIOLIB_ERR_NONE) {
      Serial.println(F("success!"));
    } else {
      Serial.print(F("failed, code "));
      Serial.println(state);
    }
  }
}


#include <RadioLib.h>
#include <SPI.h>

// Pines SX1262 (ajusta si tu placa usa otros)
#define LORA_NSS   5
#define LORA_DIO1  14
#define LORA_RST   12
#define LORA_BUSY  13

SX1262 radio = new Module(LORA_NSS, LORA_DIO1, LORA_RST, LORA_BUSY);

void setup() {
  Serial.begin(115200);
  delay(1000);

  // SPI por defecto del ESP32
  SPI.begin(18, 19, 23, LORA_NSS);

  Serial.print("Iniciando LoRa 868 MHz... ");
  int state = radio.begin(868.0);   // 🇪🇺 Europa

  if (state != RADIOLIB_ERR_NONE) {
    Serial.print("Error ");
    Serial.println(state);
    while (true);
  }

  Serial.println("OK");
  Serial.println("Esperando mensajes...");

  radio.startReceive();
}

void loop() {
  if (radio.available()) {
    String msg;

    if (radio.readData(msg) == RADIOLIB_ERR_NONE) {
      Serial.println("Mensaje recibido:");
      Serial.println(msg);
    }

    radio.startReceive();
  }
}



#include <RadioLib.h>
#include <SPI.h>

// Pines SX1262 ↔ ESP32
#define NSS   5
#define DIO1  14
#define RST   12
#define BUSY  13

#define SCK   18
#define MISO  19
#define MOSI  23

SX1262 lora = new Module(NSS, DIO1, RST, BUSY);

void setup() {
  Serial.begin(115200);
  delay(2000);

  SPI.begin(SCK, MISO, MOSI, NSS);

  Serial.println("Iniciando SX1262...");

  int state = lora.begin(868.0);
  if (state != RADIOLIB_ERR_NONE) {
    Serial.print("ERROR begin: ");
    Serial.println(state);
    while (true);
  }

  // 🔹 Spreading Factor 7
  state = lora.setSpreadingFactor(7);
  if (state != RADIOLIB_ERR_NONE) {
    Serial.print("ERROR SF: ");
    Serial.println(state);
    while (true);
  }

  Serial.println("LoRa OK (868 MHz, SF7)");
  lora.startReceive();
}

void loop() {
  if (lora.available()) {
    String msg;
    int state = lora.readData(msg);

    if (state == RADIOLIB_ERR_NONE) {
      Serial.println("RX:");
      Serial.println(msg);
    } else {
      Serial.print("RX error: ");
      Serial.println(state);
    }

    lora.startReceive();
  }
}

Parámetros implícitos (por defecto)

Este código usa automáticamente:

  • BW: 125 kHz

  • CR: 4/5

  • CRC: ON

  • Sync Word: LoRa privado (0x12)

Son compatibles con la mayoría de nodos LoRa.


#include <RadioLib.h>

// === Pines SX1262 LoRa NODE HF ↔ ESP32-D ===
// (los más comunes en este tipo de nodo)
#define LORA_NSS   5
#define LORA_DIO1  26
#define LORA_RST   27
#define LORA_BUSY  25

SX1262 lora = new Module(LORA_NSS, LORA_DIO1, LORA_RST, LORA_BUSY);

void setup() {
  Serial.begin(115200);
  delay(2000);

  Serial.println("ESP32-D + SX1262 LoRa NODE HF");

  int state = lora.begin(868.0);   // 🇪🇺 Europa
  if (state != RADIOLIB_ERR_NONE) {
    Serial.print("ERROR begin: ");
    Serial.println(state);
    while (true);
  }

  // Spreading Factor 7
  lora.setSpreadingFactor(7);

  Serial.println("LoRa listo (868 MHz, SF7)");
  Serial.println("Esperando mensajes...");

  lora.startReceive();
}

void loop() {
  if (lora.available()) {
    String msg;

    if (lora.readData(msg) == RADIOLIB_ERR_NONE) {
      Serial.println("RX:");
      Serial.println(msg);
    }

    lora.startReceive();
  }
}




#include <RadioLib.h>

// Configuración de pines SX1262
SX1262 lora = new Module(5, 21, 22, 14);  // NSS, DIO1, BUSY, RESET

void setup() {
  Serial.begin(115200);
  delay(1000);
  Serial.println("Inicializando SX1262 como Receptor...");

  // Mismos parámetros que el transmisor
  int state = lora.begin(868.0, 9, 125.0, 8, 0x12, 22, 8);
 
  if (state != RADIOLIB_ERR_NONE) {
    Serial.print("Error al iniciar SX1262. Código: ");
    Serial.println(state);
    while (true);
  }

  // Iniciar modo recepción continua
  state = lora.startReceive();
  if (state != RADIOLIB_ERR_NONE) {
    Serial.print("Error al iniciar recepción. Código: ");
    Serial.println(state);
    while (true);
  }

  Serial.println("Esperando mensajes LoRa...");
}

void loop() {
  // Verificar si hay datos recibidos
  if (lora.available()) {
    // Leer el mensaje entrante
    String mensaje = lora.readData();
   
    // Obtener métricas de la señal
    float rssi = lora.getRSSI();
    float snr = lora.getSNR();

    Serial.println("\n--- Mensaje recibido ---");
    Serial.print("Contenido: ");
    Serial.println(mensaje);
    Serial.print("RSSI: ");
    Serial.print(rssi);
    Serial.println(" dBm");
    Serial.print("SNR: ");
    Serial.print(snr);
    Serial.println(" dB");
    Serial.println("------------------------");
  }
}



Transmisor (SX1262)

#include <RadioLib.h>

// Pines para SX1262: NSS, DIO1, BUSY, RESET
SX1262 lora = new Module(5, 21, 22, 14);

void setup() {
  Serial.begin(115200);
 
  // Configuración COMPATIBLE con RFM95
  int state = lora.begin(
    868.0,    // Frecuencia (MHz)
    9,        // Spreading Factor
    125.0,    // Bandwidth (kHz)
    8,        // Coding Rate 4/8
    0x12,     // Sync Word (¡CRÍTICO!)
    17,       // Potencia (dBm)
    8         // Preamble length
  );
 
  if(state == RADIOLIB_ERR_NONE) {
    Serial.println("SX1262 listo para transmitir");
  }
}

void loop() {
  String msg = "SX1262 -> RFM95";
  lora.transmit(msg);
  delay(2000);
}

Receptor (RFM95)

#include <RadioLib.h>

// Pines para RFM95: NSS, DIO0, RESET, DIO1 (DIO1=-1 si no se usa)
RFM95 lora = new Module(10, 2, 9, -1);

void setup() {
  Serial.begin(115200);
 
  // MISMA configuración que el transmisor
  int state = lora.begin(
    868.0,    // Frecuencia (MHz)
    9,        // Spreading Factor
    125.0,    // Bandwidth (kHz)
    8,        // Coding Rate 4/8
    0x12,     // Sync Word (¡DEBE COINCIDIR!)
    17,       // Potencia (dBm)
    8         // Preamble length
  );
 
  if(state == RADIOLIB_ERR_NONE) {
    lora.startReceive();  // Modo recepción continua
    Serial.println("RFM95 listo para recibir");
  }
}

void loop() {
  if(lora.available()) {
    String msg = lora.readData();
    Serial.print("Recibido: ");
    Serial.println(msg);
  }
}









No hay comentarios: