Example Code for Arduino-OTAA Network Access

This sample code connects to the LoRaWAN network in OTAA (Over-The-Air Activation) mode. It sends data (the string "DFRobot") every 10 seconds, supports receiving downlink data and printing it, and automatically retries if the connection fails. For more sample code, please refer to the "DFRobot_LoRaWAN_ESP32S3\examples" directory.

Hardware Preparation

Software Preparation

Note:

  • LoRaWAN protocol stack version: 1.0.3
  • You need to set the data parsing format to "text" on the gateway.

Sample Code

#include "DFRobot_LoRaWAN.h"

// Data packet transmission interval
#define APP_INTERVAL_MS 10000

const uint8_t DevEUI[8] = {0xDF, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11};
const uint8_t AppEUI[8] = {0xDF, 0xB7, 0xB7, 0xB7, 0xB7, 0x00, 0x00, 0x00};
const uint8_t AppKey[16] = {
    0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 
    0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10};
uint8_t port = 2;

uint8_t buffer[255];
LoRaWAN_Node node(DevEUI, AppEUI, AppKey, CLASS_A);
TimerEvent_t appTimer;

void joinCb(bool isOk, int16_t rssi, int8_t snr)
{
    if(isOk){
        printf("JOIN SUCCESS\n");
        TimerSetValue(&appTimer, APP_INTERVAL_MS);
        TimerStart(&appTimer);
    }else{
        printf("OTAA connection error. Restart the connection request packet after 5 seconds.\n");
        delay(5000);
        node.join(joinCb);      // Rejoin the LoRaWAN network        
    }
}

void userSendUnConfirmedPacket(void)
{
    TimerSetValue(&appTimer, APP_INTERVAL_MS);
    TimerStart(&appTimer);    

    const char * data = "DFRobot"; 
    uint32_t datalen = strlen(data);
    memcpy(buffer, data, datalen);
    node.sendUnconfirmedPacket(port, buffer, /*size=*/datalen);

    printf("Sending Unconfirmed Packet...\n");
}

// Receive data callback function
void rxCb(void *buffer, uint16_t size, uint8_t port, int16_t rssi, int8_t snr, bool ackReceived, uint16_t uplinkCounter, uint16_t downlinkCounter)
{
    if(size != 0){
        printf("data:%s\n", (uint8_t*)buffer);
    }
}

void setup()
{
    Serial.begin(115200);
    delay(5000); // Open the serial port within 5 seconds after uploading to view full print output
     
    if(!(node.init(/*dataRate=*/DR_4, /*txEirp=*/16))){     // Initialize the LoRaWAN node, set the data rate and Tx Eirp
        printf("LoRaWAN Init Failed!\nPlease Check: DR or Region\n");
        while(1);
    }
    TimerInit(&appTimer, userSendUnConfirmedPacket); // Initialize timer event
    node.setRxCB(rxCb);                            // Set the callback function for receiving data
    node.join(joinCb);                             // Join the LoRaWAN network
    printf("Join Request Packet\n");
}

void loop()
{
    delay(1000);
}

Result

Result
Result

Was this article helpful?

TOP