Arduino error in error "SX126x-Arduino V2.0 does support all LoRaWAN regions without definition of 'REGION_XXYYY

Hello guys!
I’m showing all my actual Arduino code in hope to solve my actual problem.
I’m developing a project that includes the bme680 sensor that measures temperature, humidity and concentracion of gas in the surround environment.
This sensor is comunicating through i2c to a rak4630 chip and then the information goes to a lorawan gateway RAK7289v2.

My question is about the regions. I keep getting this error when i’m trying to compile the code and i’ve tried a lot of different things but all unsucessful.
My version of Arduino it’s up to date and i’ve changed/commented all the mentions to regions in Comissioning.h file and in Arduino code but the file doesn’t get compiled. Anyone of you knows how to solve this questions?
Error message:
In file included from c:\Users\jlpereira(…)\Arduino\libraries\SX126x-Arduino\src/mac/LoRaMacHelper.h:26,
from c:\Users\jlpereira(…)\Arduino\libraries\SX126x-Arduino\src/LoRaWan-Arduino.h:17,
from c:\Users\jlpereira(…)\Arduino\libraries\SX126x-Arduino\src/LoRaWan-RAK4630.h:4,
from C:\Users\jlpereira(…)\Arduino\bme_test_1\bme_test_1.ino:6:
c:\Users\jlpereira(…)\libraries\SX126x-Arduino\src/mac/Commissioning.h:42:2: error: #error “SX126x-Arduino V2.0 does support all LoRaWAN regions without definition of 'REGION_XXYYY.\n\n”
42 | #error “SX126x-Arduino V2.0 does support all LoRaWAN regions without definition of 'REGION_XXYYY.\n\nPlease read detailed information how to use it on SX126x-Arduino/README_V2.md at master · beegee-tokyo/SX126x-Arduino · GitHub
| ^~~~~
exit status 1

Compilation error: exit status 1

All Arduino code:

#include <Wire.h>                  // I2C
//#include <Adafruit-Sensor.h>
#include <Adafruit_BME680.h>       // Biblioteca para o BME680
//#include <LoRaWan-Arduino.h>
#include <SX126x-RAK4630.h>
#include <LoRaWan-RAK4630.h>       // LoRaWAN
//#include <ArduinoLowPower.h>       // Modo de baixo consumo

//#define ACTIVE_REG LORAMAC_REGION_EU868

// Configuração do BME680
#define I2C_ADDR 0x77 // Endereço default I2C do sensor
// Inicialização de uma estrutura para o sensor no endereço default para comunicar através de I2C
Adafruit_BME680 bme(I2C_ADDR);

// Configuração bateria 3,7V
// Tensão (mV) = leitura do ADC * fator de conversão do ADC
#define VBAT_PIN A0 //pin ADC p/leitura da bateria

uint32_t bateria = VBAT_PIN; 

#define VBAT_MV_PER_LSB 0.73242188 //// Conversão do ADC: 3.0V ADC range / 4096 (12 bits)
#define VBAT_DIVIDER_COMP 1.73 // Fator de compensação do divisor resistivo
#define REAL_VBAT_MV_PER_LSB (VBAT_DIVIDER_COMP * VBAT_MV_PER_LSB)

/****** Dados LoRaWAN **********/
#define LORAWAN_APP_INTERVAL 5400000 // Intervalo de 1h30min (em ms) 1000(ms)*60(s)*90(min) = 5 400 000 ms
//seleção da região EU868 para a frequência usada pelo LoRa na Europa
//LoRaMacRegion_t g_CurrentRegion = LORAMAC_REGION_EU868;
// Dados necessários para o OTAA (keys) ; MSB 
// Não vai existir configuração para OTAA ou APB, tendo em conta que por omissão ele já usa o OTAA
uint8_t nodeDeviceEUI[8] = {0xAC, 0x1F, 0x09, 0xFF, 0xFE, 0x05, 0x06, 0x8E};
uint8_t nodeAppEUI[8] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01};
uint8_t nodeAppKey[16] = {0x1F, 0xF2, 0xD9, 0xAD, 0x7C, 0xAF, 0xB7, 0xE5, 0x0E, 0xB0, 0x2A, 0xD0, 0x3E, 0x0C, 0x51, 0x6B};

// Estrutura de Callbacks
static lmh_callback_t g_lora_callbacks =
{
    BoardGetBatteryLevel,
    BoardGetUniqueId,
    BoardGetRandomSeed,
    lorawan_has_joined_handler,
    lorawan_join_fail
};

lmh_param_t lora_param_init = {
    .adr_enable = LORAWAN_ADR_ON,
    .tx_power = TX_POWER_0,
    .data_rate = DR_3,
    .public_network = LORAWAN_PUBLIC_NETWORK,
    .join_trials = 3,
    .tx_interval = 0
};

lmh_error_status lmh_init(lmh_callback_t *g_lora_callbacks, lmh_param_t lora_param_init, bool otaa, eDeviceClass nodeClass = CLASS_A, LoRaMacRegion_t region = LORAMAC_REGION_EU868);


/*****************************************************\
Chamadas o protótipo das funções antes do setup e loop
Funções desenvolvidas depois do loop()
\*****************************************************/

float readVBAT();
uint8_t batteryPercentage(float voltage);

void lorawan_has_joined_handler(void);
void lorawan_join_fail(void); //qd dispositivo falha em conectar-se à rede
uint8_t BoardGetBatteryLevel(void);
void BoardGetUniqueId(uint8_t* id);
uint32_t BoardGetRandomSeed(void);

/*******SETUP********/

void setup() 
{
  Serial.begin(115200);
  while (!Serial);

  // Inicializar I2C e BME680
  if (!bme.begin()) 
  {
    Serial.println("Erro ao inicializar o BME680!");
    while (1);
  }
  bme.setTemperatureOversampling(BME680_OS_8X);
  bme.setHumidityOversampling(BME680_OS_4X);
  bme.setGasHeater(320, 150); //320ºC em 150ms

  // Inicializar LoRaWAN
  lora_rak4630_init();
  lmh_init(&g_lora_callbacks, g_lora_param_init, true,LORAMAC_REGION_EU868);
  
  lmh_setDevEui(nodeDeviceEUI);
  lmh_setAppEui(nodeAppEUI);
  lmh_setAppKey(nodeAppKey);
  lmh_join();
}

static int sensor_fail_count = 0;

void loop() 
{
  send_lora_frame();
  enterLowPowerMode(LORAWAN_APP_INTERVAL);
  //Deep Sleep
  //LowPower.deepSleep(LORAWAN_APP_INTERVAL);
  /*RTCWakeup(LORAWAN_APP_INTERVAL);

  // Entrar no modo de baixo consumo
  Serial.println("Entrando em modo de baixo consumo...");
  //sd_power_system_off(); // Modo de baixo consumo total */
}

void enterLowPowerMode(uint32_t interval_ms) 
{
  // Configura o temporizador do sistema
  NRF_TIMER2->TASKS_STOP = 1;
  NRF_TIMER2->MODE = TIMER_MODE_MODE_Timer;
  NRF_TIMER2->BITMODE = TIMER_BITMODE_BITMODE_16Bit;
  NRF_TIMER2->PRESCALER = 4; // Ajustar conforme necessário
  NRF_TIMER2->CC[0] = interval_ms * 32.768; // Baseado no clock RTC
  NRF_TIMER2->TASKS_START = 1;

  // Entra no modo de baixo consumo
  sd_power_system_off();
}

void send_lora_frame(void)
{
  // Lê os dados do BME680
  if (!bme.performReading()) 
  {
    sensor_fail_count++;
    Serial.println("Erro ao realizar leitura no BME680!");
    if(sensor_fail_count >=3)
    {
      Serial.println("Muitas falhas no sensor. A reiniciar...");
      NVIC_SystemReset();
    }
    return;
  }
  sensor_fail_count = 0; //Reset em caso de sucesso
  float temperature = bme.temperature;            // Temperatura em °C
  float humidity = bme.humidity;                  // Umidade em %
  uint32_t gas_resistance = bme.gas_resistance;   // Resistência do gás em Ohms
  float voltage = readVBAT();
  uint8_t battery = batteryPercentage(voltage);

  //Enviar dados via LoRaWAN
  uint8_t lora_payload[7];
  lora_payload[0] = (int8_t)(temperature * 10);       // Temperatura * 10 (1 byte)
  lora_payload[1] = (uint8_t)(humidity * 10);         // Humidade * 10 (1 byte)
  lora_payload[2] = (gas_resistance >> 24) & 0xFF;    // Resistência do gás (4 bytes)
  lora_payload[3] = (gas_resistance >> 16) & 0xFF;
  lora_payload[4] = (gas_resistance >> 8) & 0xFF;
  lora_payload[5] = gas_resistance & 0xFF;
  lora_payload[6] = battery;

  lmh_app_data_t app_data = {lora_payload, sizeof(lora_payload), 1, 0, 0};
  if (lmh_send(&app_data, LMH_UNCONFIRMED_MSG) == LMH_SUCCESS) 
  {
    Serial.println("Dados enviados via LoRaWAN!");
  } else 
  {
    Serial.println("Erro ao enviar dados via LoRaWAN!");
  }
} 

//Evita que o dispositivo fique preso em loops ou estados não funcionais
void lorawan_joil_fail(void)
{
  static int join_attempts = 0;
  Serial.printIn("OTAA Join falhou!");
  join_attempts++;
  if (join_attempts >= 3)
  {
    Serial.println("Máximo de tentativas feitas. A reiniciar...");
    NVIC_SystemReset(); //Reinicia o dispositivo
  } else
  {
    Serial.println("Não deu join, vai tentar novamente");
    lmh_join();
  }
}

void lorawan_has_joined_handler(void)
{
    Serial.println("OTAA Join bem-sucedido!");
    
    // Inicia e configura um temporizador para enviar dados periodicamente
    TimerSetValue(&appTimer, LORAWAN_APP_INTERVAL);
    TimerStart(&appTimer);
}

float readVBAT() 
{
  analogReference(AR_INTERNAL_3_0);
  analogReadResolution(12);
  uint16_t adc_value = analogRead(VBAT_PIN);
  return (adc_value * REAL_VBAT_MV_PER_LSB) / 1000.0; // Retorna tensão em volts
}

uint8_t batteryPercentage(float voltage) 
{
  if (voltage < 3.0) return 0; // Bateria vazia
  if (voltage > 4.2) return 100; // Bateria cheia
  return (uint8_t)((voltage - 3.0) / (4.2 - 3.0) * 100);
}

Welcome to the forum @joaopereira

There seems to be a mix-up with your libraries or the selected board.

This error usually comes when the selected board is a Heltec board, they have their own LoRa library included and it creates a conflict with the SX126x-Arduino library.

Thanks for the answer, but that’s not the case. My board is a RAK4631 with a RAK4630 chip.
I think it could be the version of Arduino. My version is 2.3.3 and I don’t know if that’s the reason that could bring this errors.

I also tested in 2.2.1 version and it shows the same error. I haven’t got a clue what could be wrong…

Your code has many errors and typos, the error message you see is irrelevant.

(1) there is no printIn function, it is a typo, you used capital letter I instead of lowercase l

Serial.printIn("OTAA Join falhou!");

(2) you are using a reference to appTimer but it is nowhere defined

	TimerSetValue(&appTimer, LORAWAN_APP_INTERVAL);
	TimerStart(&appTimer);

(3) you are using a member in a structure that doesn’t exist.
.data_rate should be t_.data_rate
public_network should be enable_public_network
join_trials should be nb_trials
there is no tx_interval at all in that structure

lmh_param_t lora_param_init = {
	.adr_enable = LORAWAN_ADR_ON,
	.tx_power = TX_POWER_0,
	.data_rate = DR_3,
	.public_network = LORAWAN_PUBLIC_NETWORK,
	.join_trials = 3,
	.tx_interval = 0};

(4) lmh_callback_t structure is setup wrong

static lmh_callback_t g_lora_callbacks =
	{
		BoardGetBatteryLevel,
		BoardGetUniqueId,
		BoardGetRandomSeed,
		lorawan_has_joined_handler,
		lorawan_join_fail};

should be

static lmh_callback_t g_lora_callbacks =
	{
		BoardGetBatteryLevel,
		BoardGetUniqueId,
		BoardGetRandomSeed,
                NULL, // if RX callback is not used
		lorawan_has_joined_handler,
		NULL, // if Confirm Class callback is not used
		lorawan_join_fail
		NULL, // if Unconfirmed finished callback is not used
		NULL // if Confirmed finished callback is not used
};

(6) g_lora_param_init is used in the lmh_init() call,but the declaration says lora_param_init

At that point I am giving up, I guess there are more errors in your source code.
Your code looks like a wild copy&paste from other source codes.

You’re right, i had many errors but i guess from trying very different perspectives and then i ended up to do a lot of errors.
Meanwhile i fixed all the points that you analise and i keep on getting the same error.
In SX126x-Arduino/README_V2.md at master · beegee-tokyo/SX126x-Arduino · GitHub suggests to comment all the regions and i’ve tried that step but always unsucessful.

Don’t give up just yet. The code is now this way:

#include <Arduino.h>
#include <SPI.h>
#include <LoRaWan-RAK4630.h>       // LoRaWAN
#include <Wire.h>                  // I2C
//#include <Adafruit-Sensor.h>
#include <Adafruit_BME680.h>       // Biblioteca para o BME680

// RAK4630 supply two LED
#ifndef LED_BUILTIN
#define LED_BUILTIN 35
#endif

#ifndef LED_BUILTIN2
#define LED_BUILTIN2 36
#endif

(...)

/*******PARÂMETROS LORAWAN*********/
bool doOTAA = true;   // OTAA is used by default.
#define SCHED_MAX_EVENT_DATA_SIZE APP_TIMER_SCHED_EVENT_DATA_SIZE /**< Maximum size of scheduler events. */
#define SCHED_QUEUE_SIZE 60										  /**< Maximum number of events in the scheduler queue. */
#define LORAWAN_DATERATE DR_3 /*LoRaMac datarates definition, from DR_0 to DR_5*/
#define LORAWAN_TX_POWER TX_POWER_0	/*LoRaMac tx power definition, from TX_POWER_0 to TX_POWER_15*/
#define JOINREQ_NBTRIALS 3										  /**< Number of trials for the join request. */
DeviceClass_t g_CurrentClass = CLASS_A;					/* class definition*/
LoRaMacRegion_t g_CurrentRegion = LORAMAC_REGION_EU868;   
lmh_confirm g_CurrentConfirm = LMH_UNCONFIRMED_MSG;	 /* confirm/unconfirm packet definition*/
uint8_t gAppPort = LORAWAN_APP_PORT; /*definido como 2 em LoRaMacHelper.h*/

static lmh_param_t g_lora_param_init = {LORAWAN_ADR_ON, LORAWAN_DATERATE,LORAWAN_PUBLIC_NETWORK, JOINREQ_NBTRIALS, LORAWAN_TX_POWER, LORAWAN_DUTYCYCLE_OFF};
// Foward declaration
static void lorawan_has_joined(void);
static void lorawan_has_joined_fail(void);
//static void lorawan_rx_handler(lmh_app_data_t *app_data);
//static void lorawan_confirm_class_handler(DeviceClass_t Class);
static void send_lora_frame(void);

/**@brief Structure containing LoRaWan callback functions, needed for lmh_init()
*/
static lmh_callback_t g_lora_callbacks = {BoardGetBatteryLevel, BoardGetUniqueId, BoardGetRandomSeed,
                                       NULL, lorawan_has_joined, NULL, lmh_has_join_failed, NULL,NULL
};                                      
// Dados necessários para o OTAA (keys) ; MSB 
// Não vai existir configuração para OTAA ou APB, tendo em conta que por omissão ele já usa o OTAA
uint8_t nodeDeviceEUI[8] = {0xAC, 0x1F, 0x09, 0xFF, 0xFE, 0x05, 0x06, 0x8E};
uint8_t nodeAppEUI[8] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01};
uint8_t nodeAppKey[16] = {0x1F, 0xF2, 0xD9, 0xAD, 0x7C, 0xAF, 0xB7, 0xE5, 0x0E, 0xB0, 0x2A, 0xD0, 0x3E, 0x0C, 0x51, 0x6B};

// Private defination
#define LORAWAN_APP_DATA_BUFF_SIZE 64 /**< buffer size of the data to be transmitted. */
#define LORAWAN_APP_INTERVAL 20000 /**< Defines for user timer, the application data transmission interval. 20s, value in [ms]. */
static uint8_t lora_payload[LORAWAN_APP_DATA_BUFF_SIZE]; //< Lora user application data buffer.
static lmh_app_data_t app_data = {lora_payload, sizeof(lora_payload), gAppPort, 0, 0}; //< Lora user application data structure.

TimerEvent_t appTimer;
static uint32_t timers_init(void);
static uint32_t count = 0;
static uint32_t count_fail = 0;

/*******SETUP********/

void setup() 
{
  Serial.begin(115200);
  while (!Serial);

  // Inicializar I2C e BME680
  if (!bme.begin()) 
  {
    Serial.println("Erro ao inicializar o BME680!");
    while (1);
  }

  Serial.println("=====================================");

  bme.setTemperatureOversampling(BME680_OS_8X);
  bme.setHumidityOversampling(BME680_OS_4X);
  bme.setGasHeater(320, 150); //320ºC em 150ms

  // Inicializar LoRaWAN
  lora_rak4630_init();
  lmh_init(&g_lora_callbacks, g_lora_param_init, doOTAA, g_CurrentClass, g_currentRegion);
  
  lmh_setDevEui(nodeDeviceEUI);
  lmh_setAppEui(nodeAppEUI);
  lmh_setAppKey(nodeAppKey);
  lmh_join();
}

static int sensor_fail_count = 0;

void loop() 
{
  send_lora_frame();
  enterLowPowerMode(LORAWAN_APP_INTERVAL);
  //Deep Sleep
  //LowPower.deepSleep(LORAWAN_APP_INTERVAL);
  /*RTCWakeup(LORAWAN_APP_INTERVAL);

  // Entrar no modo de baixo consumo
  Serial.println("Entrando em modo de baixo consumo...");
  //sd_power_system_off(); // Modo de baixo consumo total */
}

void enterLowPowerMode(uint32_t interval_ms) 
{
  // Configura o temporizador do sistema
  NRF_TIMER2->TASKS_STOP = 1;
  NRF_TIMER2->MODE = TIMER_MODE_MODE_Timer;
  NRF_TIMER2->BITMODE = TIMER_BITMODE_BITMODE_16Bit;
  NRF_TIMER2->PRESCALER = 4; // Ajustar conforme necessário
  NRF_TIMER2->CC[0] = interval_ms * 32.768; // Baseado no clock RTC
  NRF_TIMER2->TASKS_START = 1;

  // Entra no modo de baixo consumo
  sd_power_system_off();
}

void send_lora_frame(void)
{
  // Lê os dados do BME680
  if (!bme.performReading()) 
  {
    sensor_fail_count++;
    Serial.println("Erro ao realizar leitura no BME680!");
    if(sensor_fail_count >=3)
    {
      Serial.println("Muitas falhas no sensor. A reiniciar...");
      NVIC_SystemReset();
    }
    return;
  }
  sensor_fail_count = 0; //Reset em caso de sucesso
  float temperature = bme.temperature;            // Temperatura em °C
  float humidity = bme.humidity;                  // Umidade em %
  uint32_t gas_resistance = bme.gas_resistance;   // Resistência do gás em Ohms
  float voltage = readVBAT();
  uint8_t battery = batteryPercentage(voltage);

  //Enviar dados via LoRaWAN
  uint8_t lora_payload[7];
  lora_payload[0] = (int8_t)(temperature * 10);       // Temperatura * 10 (1 byte)
  lora_payload[1] = (uint8_t)(humidity * 10);         // Humidade * 10 (1 byte)
  lora_payload[2] = (gas_resistance >> 24) & 0xFF;    // Resistência do gás (4 bytes)
  lora_payload[3] = (gas_resistance >> 16) & 0xFF;
  lora_payload[4] = (gas_resistance >> 8) & 0xFF;
  lora_payload[5] = gas_resistance & 0xFF;
  lora_payload[6] = battery;

  //lmh_app_data_t app_data = {&lora_payload, sizeof(lora_payload), 1, 0, 0};
  if (lmh_send(&app_data, LMH_UNCONFIRMED_MSG) == LMH_SUCCESS) 
  {
    Serial.println("Dados enviados via LoRaWAN!");
  } else 
  {
    Serial.println("Erro ao enviar dados via LoRaWAN!");
  }
} 

//Evita que o dispositivo fique preso em loops ou estados não funcionais
void lorawan_has_joined_fail(void)
{
  static int join_attempts = 0;
  Serial.println("OTAA Join falhou!");
  join_attempts++;
  if (join_attempts >= 3)
  {
    Serial.println("Máximo de tentativas feitas. A reiniciar...");
    NVIC_SystemReset(); //Reinicia o dispositivo
  } else
  {
    Serial.println("Não deu join, vai tentar novamente");
    lmh_join();
  }
}

void lorawan_has_joined(void)
{
    Serial.println("OTAA Join bem-sucedido!");
    
    // Inicia e configura um temporizador para enviar dados periodicamente
    TimerSetValue(&appTimer, LORAWAN_APP_INTERVAL);
    TimerStart(&appTimer);
}

(...)

some parts of the code are not here because i think i put what's most important for the error. If anyone could explain me what i'm doing wrong, i would be grateful

it’s compiling now, thank you for the help.