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 pinesSX1262 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 necesarioif (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
-
Abrir Arduino IDE
-
Ir al menú:
Sketch → Include Library → Manage Libraries… -
En la barra de búsqueda escribir:
RadioLib -
Aparecerá:
RadioLib – Jan Gromes -
Hacer clic en Install
-
Esperar a que termine la instalación
// 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); }
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);
#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
/*RadioLib SX126x Blocking Receive ExampleThis example listens for LoRa transmissions using SX126x Lora modules.To successfully receive data, the following settings have to be the sameon both transmitter and receiver:- carrier frequency- bandwidth- spreading factor- coding rate- sync word- preamble lengthOther modules from SX126x family can also be used.Using blocking receive is not recommended, as it will leadto significant amount of timeouts, inefficient use of processortime and can some miss packets!Instead, interrupt receive is recommended.For default module settings, see the wiki pagehttps://github.com/jgromes/RadioLib/wiki/Default-configuration#sx126x---lora-modemFor full API reference, see the GitHub Pageshttps://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: 9SX1262 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 settingsSerial.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 StringString 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 receivedSerial.println(F("success!"));// print the data of the packetSerial.print(F("[SX1262] Data:\t\t"));Serial.println(str);// print the RSSI (Received Signal Strength Indicator)// of the last received packetSerial.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 packetSerial.print(F("[SX1262] SNR:\t\t"));Serial.print(radio.getSNR());Serial.println(F(" dB"));// print frequency errorSerial.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 packetSerial.println(F("timeout!"));} else if (state == RADIOLIB_ERR_CRC_MISMATCH) {// packet was received, but is malformedSerial.println(F("CRC error!"));} else {// some other error occurredSerial.print(F("failed, code "));Serial.println(state);}}
/*RadioLib SX126x Channel Activity Detection ExampleThis example uses SX1262 to scan the current LoRachannel and detect ongoing LoRa transmissions.Unlike SX127x CAD, SX126x can detect any partof LoRa transmission, not just the preamble.Other modules from SX126x family can also be used.For default module settings, see the wiki pagehttps://github.com/jgromes/RadioLib/wiki/Default-configuration#sx126x---lora-modemFor full API reference, see the GitHub Pageshttps://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: 9SX1262 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 settingsSerial.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 detectedradio.setDio1Action(setFlag);// start scanning the channelSerial.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 outvolatile 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#endifvoid setFlag(void) {// something happened, set the flagscanFlag = true;}void loop() {// check if the flag is setif(scanFlag) {// reset flagscanFlag = false;// check CAD resultint state = radio.getChannelScanResult();if (state == RADIOLIB_LORA_DETECTED) {// LoRa packet was detectedSerial.println(F("[SX1262] Packet detected!"));} else if (state == RADIOLIB_CHANNEL_FREE) {// channel is freeSerial.println(F("[SX1262] Channel is free!"));} else {// some other error occurredSerial.print(F("[SX1262] Failed, code "));Serial.println(state);}// start scanning the channel againSerial.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 13SX1262 radio = new Module(LORA_NSS, LORA_DIO1, LORA_RST, LORA_BUSY);void setup() {Serial.begin(115200);delay(1000);// SPI por defecto del ESP32SPI.begin(18, 19, 23, LORA_NSS);Serial.print("Iniciando LoRa 868 MHz... ");int state = radio.begin(868.0); // 🇪🇺 Europaif (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 23SX1262 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 7state = 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 25SX1262 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); // 🇪🇺 Europaif (state != RADIOLIB_ERR_NONE) {Serial.print("ERROR begin: ");Serial.println(state);while (true);}// Spreading Factor 7lora.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 SX1262SX1262 lora = new Module(5, 21, 22, 14); // NSS, DIO1, BUSY, RESETvoid setup() {Serial.begin(115200);delay(1000);Serial.println("Inicializando SX1262 como Receptor...");// Mismos parámetros que el transmisorint 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 continuastate = 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 recibidosif (lora.available()) {// Leer el mensaje entranteString mensaje = lora.readData();// Obtener métricas de la señalfloat 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("------------------------");}}


No hay comentarios:
Publicar un comentario