/* * ESP32 Plane Radar * Plots live ADS-B aircraft on a GC9A01 1.28-inch round display. * First-boot softAP portal (192.168.4.1) stores Wi-Fi + location in NVS. * BOOT button (GPIO9) cycles radar range 5 → 10 → 15 → 25 km. * Hold BOOT for 3 s to clear saved credentials and relaunch the portal. * * Inspired by MatixYo's ESP32-Plane-Radar: https://github.com/MatixYo/ESP32-Plane-Radar */ #include #include #include #include #include #include #include #include #include // ── Pin assignments ────────────────────────────────────────────────────────── #define RADAR_RST 0 #define RADAR_CS 1 #define RADAR_DC 10 #define RADAR_MOSI 3 #define RADAR_SCLK 4 #define BOOT_BUTTON 9 // ── Radar settings ─────────────────────────────────────────────────────────── #define FETCH_INTERVAL_MS 5000 #define HOLD_CLEAR_MS 3000 // hold BOOT this long to wipe credentials #define AP_SSID "PlaneRadar-Setup" #define NVS_NAMESPACE "planeradar" #define DISPLAY_SIZE 240 #define DISPLAY_CENTER 120 #define DISPLAY_RADIUS 105 // outermost radar ring // ── Math helpers ───────────────────────────────────────────────────────────── static const double DEG2RAD = M_PI / 180.0; // Returns great-circle distance in kilometres between two lat/lon points. double haversineKm(double lat1, double lon1, double lat2, double lon2) { double dlat = (lat2 - lat1) * DEG2RAD; double dlon = (lon2 - lon1) * DEG2RAD; double a = sin(dlat / 2) * sin(dlat / 2) + cos(lat1 * DEG2RAD) * cos(lat2 * DEG2RAD) * sin(dlon / 2) * sin(dlon / 2); return 6371.0 * 2.0 * atan2(sqrt(a), sqrt(1.0 - a)); } // Returns initial bearing in degrees (0 = north, clockwise) from p1 to p2. double initialBearing(double lat1, double lon1, double lat2, double lon2) { double dlon = (lon2 - lon1) * DEG2RAD; double y = sin(dlon) * cos(lat2 * DEG2RAD); double x = cos(lat1 * DEG2RAD) * sin(lat2 * DEG2RAD) - sin(lat1 * DEG2RAD) * cos(lat2 * DEG2RAD) * cos(dlon); double bearing = atan2(y, x) / DEG2RAD; return fmod(bearing + 360.0, 360.0); } // ── LovyanGFX display class ────────────────────────────────────────────────── class RadarDisplay : public lgfx::LGFX_Device { lgfx::Bus_SPI _bus; lgfx::Panel_GC9A01 _panel; public: RadarDisplay() { auto busCfg = _bus.config(); busCfg.spi_host = SPI2_HOST; busCfg.freq_write = 40000000; busCfg.pin_sclk = RADAR_SCLK; busCfg.pin_mosi = RADAR_MOSI; busCfg.pin_miso = -1; busCfg.pin_dc = RADAR_DC; _bus.config(busCfg); _panel.setBus(&_bus); auto panelCfg = _panel.config(); panelCfg.pin_cs = RADAR_CS; panelCfg.pin_rst = RADAR_RST; panelCfg.invert = true; panelCfg.rgb_order = true; _panel.config(panelCfg); setPanel(&_panel); } }; // ── Globals ────────────────────────────────────────────────────────────────── RadarDisplay display; Preferences prefs; WebServer configServer(80); float radarRangeKm = 10.0f; static constexpr double BEDFORD_LAT = 42.49056; static constexpr double BEDFORD_LON = -71.27667; double radarLat = BEDFORD_LAT; double radarLon = BEDFORD_LON; String lastScene; bool configMode = false; unsigned long lastFetchMs = 0; unsigned long bootPressedAt = 0; bool bootWasLow = false; // ── Forward declarations ───────────────────────────────────────────────────── void drawRadarShell(); void drawAircraft(float bearingDeg, float distanceKm, const char* label); void fetchAircraft(); void startConfigPortal(); void handleConfigRoot(); void handleConfigSave(); void showMessage(const char* line1, const char* line2 = nullptr); // ── Display helpers ────────────────────────────────────────────────────────── // Approximate town centers, not streets or municipal boundaries. struct Town { const char* name; double lat; double lon; }; static const Town towns[] = { {"BEDFORD", BEDFORD_LAT, BEDFORD_LON}, {"Lexington", 42.44732, -71.22450}, {"Billerica", 42.55833, -71.26944}, {"Concord", 42.46028, -71.34944}, {"Chelsford", 42.5987138, -71.363625}, {"Winchester", 42.4528, -71.1443}, {"Weston", 42.3668, -71.3031}, {"Boston", 42.3611, -71.0571}, {"Reading", 42.5257, -71.095}, {"Carlisle", 42.5292597, -71.3495046}, {"Burlington", 42.504716, -71.195621}, {"Waltham", 42.3765, -71.2356} }; void drawTowns() { display.setTextSize(1); display.setTextColor(TFT_CYAN, TFT_BLACK); for (const Town& town : towns) { double distance = haversineKm(radarLat, radarLon, town.lat, town.lon); if (distance > radarRangeKm) continue; double angle = (initialBearing(radarLat, radarLon, town.lat, town.lon) - 90) * DEG2RAD; double radius = distance / radarRangeKm * DISPLAY_RADIUS; int x = DISPLAY_CENTER + lround(cos(angle) * radius); int y = DISPLAY_CENTER + lround(sin(angle) * radius); display.drawCircle(x, y, 2, TFT_CYAN); int width = display.textWidth(town.name); // Center labels below their markers and keep them within the round face. int labelY = y + 5; int halfChord = (int)sqrt(fmax(0.0, 112.0 * 112.0 - pow(abs(labelY + 4 - 120), 2))); int labelX = constrain(x - width / 2, 120 - halfChord, 120 + halfChord - width); display.drawString(town.name, labelX, labelY); } } void drawRadarShell() { lastScene = ""; display.fillScreen(TFT_BLACK); display.drawCircle(DISPLAY_CENTER, DISPLAY_CENTER, DISPLAY_RADIUS, TFT_GREEN); display.drawCircle(DISPLAY_CENTER, DISPLAY_CENTER, 78, TFT_DARKGREEN); display.drawCircle(DISPLAY_CENTER, DISPLAY_CENTER, 52, TFT_DARKGREEN); display.drawCircle(DISPLAY_CENTER, DISPLAY_CENTER, 26, TFT_DARKGREEN); display.drawLine(15, DISPLAY_CENTER, 225, DISPLAY_CENTER, TFT_BLUE); display.drawLine(DISPLAY_CENTER, 15, DISPLAY_CENTER, 225, TFT_BLUE); display.setTextColor(TFT_WHITE, TFT_BLACK); display.setTextSize(2); display.drawString("N", 116, 8); display.drawString("S", 116, 221); display.drawString("W", 6, 116); display.drawString("E", 225, 116); drawTowns(); // Range label bottom-right char rangeBuf[8]; snprintf(rangeBuf, sizeof(rangeBuf), "%dkm", (int)radarRangeKm); display.setTextColor(TFT_YELLOW, TFT_BLACK); display.drawString(rangeBuf, 195, 218); } void drawAircraft(float bearingDeg, float distanceKm, const char* label) { if (distanceKm > radarRangeKm) return; // bearingDeg is 0=north, rotate so north = up (subtract 90° for screen coords) float angle = (bearingDeg - 90.0f) * DEG_TO_RAD; float radius = (distanceKm / radarRangeKm) * (float)DISPLAY_RADIUS; int px = DISPLAY_CENTER + (int)(cosf(angle) * radius); int py = DISPLAY_CENTER + (int)(sinf(angle) * radius); // Small filled triangle pointing north display.fillTriangle(px, py - 5, px - 4, py + 4, px + 4, py + 4, TFT_RED); display.setTextColor(TFT_WHITE, TFT_BLACK); display.setTextSize(1); display.drawString(label, constrain(px + 6, 0, 190), constrain(py - 8, 0, 230)); } void showMessage(const char* line1, const char* line2) { display.fillScreen(TFT_BLACK); display.setTextColor(TFT_WHITE, TFT_BLACK); display.setTextSize(1); display.drawString(line1, 20, 110); if (line2) display.drawString(line2, 20, 125); } // ── Config portal ──────────────────────────────────────────────────────────── // Small HTML form served over softAP — stores SSID/password/lat/lon in NVS. // This replaces WiFiManager to keep binary size under the 1 280 KB app partition. static const char CONFIG_HTML[] PROGMEM = R"rawhtml( PlaneRadar Setup

PlaneRadar Setup

Enter your Wi-Fi details. Radar center: Bedford, Massachusetts.

Nearby town markers: Lexington, Billerica and Concord.

)rawhtml"; static const char SAVED_HTML[] PROGMEM = R"rawhtml( Saved

Saved!

The radar is connecting to your Wi-Fi. You can close this page.

)rawhtml"; void handleConfigRoot() { configServer.send(200, "text/html", CONFIG_HTML); } void handleConfigSave() { String ssid = configServer.arg("ssid"); String pass = configServer.arg("pass"); prefs.begin(NVS_NAMESPACE, false); prefs.putString("ssid", ssid); prefs.putString("pass", pass); prefs.end(); configServer.send(200, "text/html", SAVED_HTML); delay(1500); ESP.restart(); } void startConfigPortal() { configMode = true; WiFi.mode(WIFI_AP); WiFi.softAP(AP_SSID); Serial.print("Config portal at: "); Serial.println(WiFi.softAPIP()); configServer.on("/", HTTP_GET, handleConfigRoot); configServer.on("/save", HTTP_POST, handleConfigSave); configServer.begin(); showMessage("PlaneRadar-Setup", "192.168.4.1"); } // ── Aircraft fetch ──────────────────────────────────────────────────────────── void fetchAircraft() { if (WiFi.status() != WL_CONNECTED) return; // opendata.adsb.fi: dist is nautical miles; convert km → nm (1 nm = 1.852 km) // adsb.fi is HTTPS-only (plain HTTP gets a 301 the ESP32 HTTPClient will // not follow). setInsecure() skips certificate validation: this is public, // read-only flight data, and the C3's 1.25 MB app partition has no room // for a CA bundle on top of the TLS stack. float nm = radarRangeKm / 1.852f; WiFiClientSecure client; client.setInsecure(); String url = "https://opendata.adsb.fi/api/v3/lat/" + String(radarLat, 5) + "/lon/" + String(radarLon, 5) + "/dist/" + String(nm, 1); HTTPClient http; http.begin(client, url); http.setTimeout(4000); int code = http.GET(); if (code == HTTP_CODE_OK) { // HTTPClient decodes HTTP chunk framing; the raw stream does not. String payload = http.getString(); JsonDocument doc; DeserializationError err = deserializeJson(doc, payload); if (err) { Serial.printf("JSON error: %s\n", err.c_str()); http.end(); return; } // Ignore server timestamps: repaint only if aircraft or range changes. String scene = String(radarRangeKm, 0); for (JsonObject plane : doc["ac"].as()) { if (!plane["lat"].is() || !plane["lon"].is()) continue; if (haversineKm(radarLat, radarLon, plane["lat"].as(), plane["lon"].as()) > radarRangeKm) continue; const char* label = plane["flight"] | plane["hex"] | "AC"; scene += "|" + String(plane["lat"].as(), 6) + "," + String(plane["lon"].as(), 6) + label; } if (scene == lastScene) { http.end(); return; } drawRadarShell(); lastScene = scene; int plotted = 0; for (JsonObject plane : doc["ac"].as()) { if (!plane["lat"].is() || !plane["lon"].is()) continue; double acLat = plane["lat"].as(); double acLon = plane["lon"].as(); double distKm = haversineKm(radarLat, radarLon, acLat, acLon); double bearDeg = initialBearing(radarLat, radarLon, acLat, acLon); if (distKm > radarRangeKm) continue; // outside current range // Label preference: flight callsign → ICAO hex → fallback "AC" const char* label = plane["flight"] | plane["hex"] | "AC"; drawAircraft((float)bearDeg, (float)distKm, label); plotted++; } Serial.printf("Plotted %d aircraft within %.0f km\n", plotted, radarRangeKm); } else { Serial.printf("HTTP error: %d\n", code); } http.end(); } // ── Setup ───────────────────────────────────────────────────────────────────── void setup() { Serial.begin(115200); pinMode(BOOT_BUTTON, INPUT_PULLUP); display.init(); display.setRotation(0); display.setTextSize(1); drawRadarShell(); // Load saved credentials from NVS prefs.begin(NVS_NAMESPACE, true); String savedSsid = prefs.getString("ssid", ""); String savedPass = prefs.getString("pass", ""); // Fixed Bedford center overrides old location settings, but preserves Wi-Fi. radarLat = BEDFORD_LAT; radarLon = BEDFORD_LON; prefs.end(); if (savedSsid.length() == 0) { Serial.println("No credentials — starting config portal"); startConfigPortal(); return; } showMessage("Connecting to WiFi...", savedSsid.c_str()); WiFi.mode(WIFI_STA); WiFi.begin(savedSsid.c_str(), savedPass.c_str()); unsigned long t0 = millis(); while (WiFi.status() != WL_CONNECTED && millis() - t0 < 15000) { delay(250); } if (WiFi.status() != WL_CONNECTED) { Serial.println("Wi-Fi failed — starting config portal"); startConfigPortal(); return; } Serial.printf("Connected. IP: %s Lat: %.4f Lon: %.4f\n", WiFi.localIP().toString().c_str(), radarLat, radarLon); drawRadarShell(); } // ── Loop ────────────────────────────────────────────────────────────────────── void loop() { if (configMode) { configServer.handleClient(); return; } // BOOT button: short press cycles range; hold 3 s clears credentials bool bootLow = (digitalRead(BOOT_BUTTON) == LOW); if (bootLow && !bootWasLow) { bootPressedAt = millis(); bootWasLow = true; } if (!bootLow && bootWasLow) { unsigned long held = millis() - bootPressedAt; bootWasLow = false; if (held >= HOLD_CLEAR_MS) { // Long press: wipe saved credentials and reboot into portal Serial.println("Long press — clearing credentials"); prefs.begin(NVS_NAMESPACE, false); prefs.clear(); prefs.end(); delay(200); ESP.restart(); } else { // Short press: cycle range if (radarRangeKm == 5) radarRangeKm = 10; else if (radarRangeKm == 10) radarRangeKm = 15; else if (radarRangeKm == 15) radarRangeKm = 25; else radarRangeKm = 5; Serial.printf("Range → %.0f km\n", radarRangeKm); drawRadarShell(); } } // Fetch every FETCH_INTERVAL_MS if (millis() - lastFetchMs >= FETCH_INTERVAL_MS) { lastFetchMs = millis(); fetchAircraft(); } }