# main.ino

- Project: [esp32-nRF24-example](https://flashesp.com/explore/5ZsFixtYO2RXHR3ncfWBl.md) by Mikrobot.pl
- Board: ESP32 Dev Module
- Language: Arduino (C++)
- Web page: https://flashesp.com/explore/5ZsFixtYO2RXHR3ncfWBl/files/baiFV70izjd0ZGRBb35ZN

```cpp
#include <WiFi.h>
#include <WebServer.h>
#include <DNSServer.h>
#include <SPI.h>
#include <RF24.h>

// =======================
// nRF24L01+ PIN CONFIGURATION (ESP32 - VSPI)
// =======================
// SPI (fixed VSPI pins on most ESP32 dev boards):
//   SCK  -> GPIO 18
//   MISO -> GPIO 19
//   MOSI -> GPIO 23
// User selectable control pins:
#define CE_PIN   4    // Chip Enable
#define CSN_PIN  5    // SPI Chip Select

// RF24 radio object
RF24 radio(CE_PIN, CSN_PIN);

// =======================
// TEST RESULT STORAGE
// =======================
struct TestResult {
  bool     beginOk;        // radio.begin() succeeded
  bool     chipConnected;  // SPI communication alive
  bool     plusVariant;    // true = genuine nRF24L01+ (not clone/older)
  bool     channelOk;      // channel write/read-back match
  bool     dataRateOk;     // data-rate write/read-back match
  uint8_t  channelWritten; // value written to RF_CH
  uint8_t  channelRead;    // value read back from RF_CH
  uint8_t  dataRate;       // 0=1MBPS, 1=2MBPS, 2=250KBPS
  uint8_t  paLevel;        // power amplifier level
  bool     allPassed;      // overall verdict
  bool     hasRun;         // test has been executed at least once
};

// order: beginOk, chipConnected, plusVariant, channelOk, dataRateOk,
//        channelWritten, channelRead, dataRate, paLevel, allPassed, hasRun
TestResult testResult = { false, false, false, false, false, 0, 0, 0, 0, false, false };

// =======================
// WIFI ACCESS POINT CONFIG
// =======================
const char* ap_ssid = "ESP32-nRF24-Test"; // open AP (no password)

IPAddress apIP(192, 168, 4, 1);
IPAddress netMsk(255, 255, 255, 0);

// =======================
// DNS / CAPTIVE PORTAL
// =======================
const byte DNS_PORT = 53;

DNSServer dnsServer;
WebServer server(80);

// =======================
// nRF24L01+ TEST ROUTINE
// =======================
void runRadioTest() {
  TestResult r = { false, false, false, false, false, 0, 0, 0, 0, false, false };

  // 1) Initialize the radio / SPI
  r.beginOk = radio.begin();

  // 2) Verify the chip actually answers over SPI.
  //    If MISO is stuck (disconnected / bad wiring) reads return 0x00 or 0xFF
  //    and isChipConnected() reports false.
  r.chipConnected = radio.isChipConnected();

  if (r.beginOk && r.chipConnected) {
    // 3) Detect the "+" (plus) variant. True nRF24L01+ supports 250 kbps.
    r.plusVariant = radio.isPVariant();

    // 4) Write/read-back test on the RF channel register (RF_CH).
    //    Proves both write AND read paths of the SPI bus work.
    r.channelWritten = 108; // arbitrary test channel
    radio.setChannel(r.channelWritten);
    r.channelRead = radio.getChannel();
    r.channelOk = (r.channelRead == r.channelWritten);

    // 5) Write/read-back test on the data-rate register (RF_SETUP).
    //    A genuine '+' module must accept and report back 250 kbps.
    r.dataRateOk = radio.setDataRate(RF24_250KBPS) &&
                   (radio.getDataRate() == RF24_250KBPS);
    // Restore a common default rate afterwards
    radio.setDataRate(RF24_1MBPS);

    // 6) Grab a couple of live settings for display
    r.dataRate = (uint8_t)radio.getDataRate();
    r.paLevel  = (uint8_t)radio.getPALevel();
  }

  // Overall verdict
  r.allPassed = r.beginOk && r.chipConnected && r.plusVariant &&
                r.channelOk && r.dataRateOk;
  r.hasRun = true;

  testResult = r;

  // Also print to serial for debugging
  Serial.println("==== nRF24L01+ TEST ====");
  Serial.printf("begin()          : %s\n", r.beginOk ? "OK" : "FAIL");
  Serial.printf("chip connected   : %s\n", r.chipConnected ? "OK" : "FAIL");
  Serial.printf("plus variant     : %s\n", r.plusVariant ? "YES" : "NO");
  Serial.printf("channel RW test  : %s (wrote %d, read %d)\n",
                r.channelOk ? "OK" : "FAIL", r.channelWritten, r.channelRead);
  Serial.printf("datarate RW test : %s\n", r.dataRateOk ? "OK" : "FAIL");
  Serial.printf("VERDICT          : %s\n", r.allPassed ? "PASS" : "FAIL");
  Serial.println("========================");
}

// =======================
// HELPERS FOR DISPLAY
// =======================
String dataRateStr(uint8_t dr) {
  switch (dr) {
    case 0: return "1 Mbps";
    case 1: return "2 Mbps";
    case 2: return "250 kbps";
    default: return "?";
  }
}

String paLevelStr(uint8_t pa) {
  switch (pa) {
    case 0: return "MIN (-18 dBm)";
    case 1: return "LOW (-12 dBm)";
    case 2: return "HIGH (-6 dBm)";
    case 3: return "MAX (0 dBm)";
    default: return "?";
  }
}

String rowHtml(const String& label, bool ok, const String& detail) {
  String cls = ok ? "pass" : "fail";
  String badge = ok ? "PASS" : "FAIL";
  String html = "<tr><td>" + label + "</td>";
  html += "<td class='" + cls + "'>" + badge + "</td>";
  html += "<td>" + detail + "</td></tr>";
  return html;
}

// =======================
// HTML PAGE
// =======================
String htmlPage() {
  const TestResult& r = testResult;

  String html = "<!DOCTYPE html><html><head>"
                "<meta charset='UTF-8'>"
                "<meta name='viewport' content='width=device-width, initial-scale=1.0'>"
                "<title>ESP32 nRF24L01+ Tester</title>"
                "<style>"
                "body{font-family:sans-serif;margin:20px;background:#f4f4f4;color:#222;}"
                "h2{margin-bottom:4px;}"
                ".verdict{padding:14px;border-radius:8px;font-size:20px;font-weight:bold;"
                "color:#fff;margin:14px 0;text-align:center;}"
                ".ok{background:#2e7d32;}"
                ".bad{background:#c62828;}"
                ".none{background:#616161;}"
                "table{border-collapse:collapse;width:100%;background:#fff;"
                "box-shadow:0 1px 3px rgba(0,0,0,.15);}"
                "th,td{padding:10px;border-bottom:1px solid #ddd;text-align:left;}"
                "th{background:#333;color:#fff;}"
                ".pass{color:#2e7d32;font-weight:bold;}"
                ".fail{color:#c62828;font-weight:bold;}"
                "button{padding:12px 24px;margin:12px 0;font-size:16px;"
                "background:#1565c0;color:#fff;border:none;border-radius:6px;cursor:pointer;}"
                "button:hover{background:#0d47a1;}"
                ".hint{background:#fff3cd;border:1px solid #ffe08a;padding:10px;"
                "border-radius:6px;margin-top:14px;font-size:14px;}"
                "</style>"
                "</head><body>";

  html += "<h2>ESP32 &mdash; nRF24L01+ PA/LNA Tester</h2>";
  html += "<p>Module: <b>nRF24L01+ ISM 2.4 GHz</b> with power amplifier &amp; external antenna</p>";

  if (!r.hasRun) {
    html += "<div class='verdict none'>NO TEST RUN YET</div>";
  } else if (r.allPassed) {
    html += "<div class='verdict ok'>&#10004; MODULE OK &mdash; ALL TESTS PASSED</div>";
  } else {
    html += "<div class='verdict bad'>&#10008; MODULE FAULT &mdash; CHECK WIRING/POWER</div>";
  }

  if (r.hasRun) {
    html += "<table>";
    html += "<tr><th>Test</th><th>Result</th><th>Details</th></tr>";

    html += rowHtml("SPI init (radio.begin)", r.beginOk,
                    r.beginOk ? "SPI started" : "Cannot start SPI");

    html += rowHtml("Chip responds (SPI link)", r.chipConnected,
                    r.chipConnected ? "Registers readable"
                                    : "No answer &rarr; wiring / MISO / power");

    html += rowHtml("nRF24L01+ variant", r.plusVariant,
                    r.plusVariant ? "Genuine '+' (250 kbps capable)"
                                  : "Not detected as '+' (clone or dead)");

    html += rowHtml("Channel write/read-back", r.channelOk,
                    "wrote " + String(r.channelWritten) +
                    ", read " + String(r.channelRead));

    html += rowHtml("Data-rate 250 kbps write/read", r.dataRateOk,
                    r.dataRateOk ? "Accepted &amp; confirmed"
                                 : "Rejected on read-back");

    if (r.beginOk && r.chipConnected) {
      html += "<tr><td>Data rate</td><td>&mdash;</td><td>" + dataRateStr(r.dataRate) + "</td></tr>";
      html += "<tr><td>PA power level</td><td>&mdash;</td><td>" + paLevelStr(r.paLevel) + "</td></tr>";
    }

    html += "</table>";
  }

  html += "<form action='/test' method='GET'>";
  html += "<button type='submit'>&#8635; Run test again</button>";
  html += "</form>";

  if (r.hasRun && !r.allPassed) {
    html += "<div class='hint'><b>Troubleshooting:</b><ul>"
            "<li><b>Power:</b> PA/LNA modules draw current spikes &mdash; feed VCC from a stable "
            "3.3 V source and add a <b>10&ndash;100&nbsp;&micro;F</b> capacitor across VCC&ndash;GND.</li>"
            "<li>Never power the module from 5 V (logic is 3.3 V only).</li>"
            "<li>Check SCK=18, MISO=19, MOSI=23, CE=4, CSN=5, GND common.</li>"
            "<li>Re-seat the module and antenna; check for cold solder joints.</li>"
            "</ul></div>";
  }

  html += "<hr><p style='font-size:13px;color:#666;'>Connect to WiFi <b>ESP32-nRF24-Test</b> "
          "(open network). This page opens automatically as a captive portal.</p>";
  html += "</body></html>";

  return html;
}

// =======================
// CAPTIVE PORTAL REDIRECT
// =======================
void redirectToRoot() {
  String url = "http://" + apIP.toString() + "/";
  server.sendHeader("Location", url, true);
  server.send(302, "text/plain", "");
}

// =======================
// HTTP HANDLERS
// =======================
void handleRoot() {
  server.send(200, "text/html", htmlPage());
}

void handleTest() {
  runRadioTest();
  server.send(200, "text/html", htmlPage());
}

void handleNotFound() {
  redirectToRoot();
}

// Captive portal triggers used by Android, iOS, Windows
void handleGenerate204() { handleRoot(); } // /generate_204 (Android)
void handleHotspotDetect() { handleRoot(); } // /hotspot-detect.html (iOS/macOS)
void handleNCsi() { handleRoot(); } // /ncsi.txt (Windows)

// =======================
// SETUP
// =======================
void setup() {
  Serial.begin(115200);
  delay(100);

  // Run one test at boot so the first page already shows a result
  runRadioTest();

  // Start WiFi in AP mode (open network)
  WiFi.mode(WIFI_AP);
  WiFi.softAPConfig(apIP, apIP, netMsk);
  WiFi.softAP(ap_ssid);

  Serial.println();
  Serial.print("AP started. SSID: ");
  Serial.println(ap_ssid);
  Serial.print("AP IP address: ");
  Serial.println(apIP);

  // Start DNS server -> redirect all domains to our AP
  dnsServer.start(DNS_PORT, "*", apIP);

  // Setup web server routes
  server.on("/", handleRoot);
  server.on("/test", handleTest);

  // Captive portal paths
  server.on("/generate_204", handleGenerate204);
  server.on("/hotspot-detect.html", handleHotspotDetect);
  server.on("/ncsi.txt", handleNCsi);

  server.onNotFound(handleNotFound);
  server.begin();

  Serial.println("Web server + DNS captive portal started.");
}

// =======================
// LOOP
// =======================
void loop() {
  dnsServer.processNextRequest();
  server.handleClient();
}
```
