Simple power adaptation for NRF24L01 + Arduino + RF24 Library

in #arduino7 years ago

I needed to implement a power adaptation algorithm for my temperature sensors working in variable conditions and also lower the battery drain when the base station was off.

nRF24l01.jpg

So I came up with this:
Firstly, simply check if the receiver is on (assume that it can be reached with MAX power). If it's on then try to communicate on the lower power level. If the power level is too low, then go to the last working one. If there is no comm with the RX then go for a long sleep:

bool adaptPower() {
  for (int8_t tmp_power = RF24_PA_MAX; tmp_power >= RF24_PA_MIN; --tmp_power) {
    uint8_t tx_sent = 0;
    radio.setPALevel(tmp_power);

    for (uint8_t i = 0; i < PWR_ADAPT_TRIES; ++i) {
      tx_sent += sendData();
      sleep_tight(ON_SLEEP_CYCLES);
    }

    if (tx_sent == 0) {
      if (tmp_power == RF24_PA_MAX) {
        sleep_tight(OFF_SLEEP_CYCLES);  //assume RX is off and go for a long nap
        return false;
      } else {
        radio.setPALevel(tmp_power + 1); //adjust power to the last working level
        break;
      }
    }
  }
  return true;
}

The main loop is just checking if the limit of failed transmissions is reached, if yes then it goes back to the power adaptation:

void loop() {
  if (adaptPower()) {
    failed_txs = 0;
    while (failed_txs < FAILED_TXS_LIMIT) {
      if (sendData()) {
        failed_txs = 0; //reset counter
      } else {
        ++failed_txs;
      }
      sleep_tight(ON_SLEEP_CYCLES);
    }
  }
}

The whole sketch is here: https://pastebin.com/fVWtAhxt