Capstone Project – Scanning Sonar Server Code

C++ Code Listing

Here’s one solution to the IoT Capstone Project Challenge to produce a scanning sonar system. The project integrates earlier work for sonar range measurement, servo motor controls, OLED display, and Web access to a wireless sensor. 

This page hosts the C++ code for the solution. The companion HTML/JavaScript code is here. 

				
					/* =====================================================================================
 * ESP32 Sonar Radar — Azimuth/Range Sweep over WebSocket
 * =====================================================================================
 * Hardware:
 *   - ESP32 Dev Kit V1
 *   - HC-SR04 ultrasonic range sensor
 *   - SG90 micro servo (pans the HC-SR04 to produce an azimuth sweep)
 *
 * Wiring:
 *   HC-SR04 VCC  -> 5V
 *   HC-SR04 GND  -> GND (common with ESP32 and servo)
 *   HC-SR04 TRIG -> GPIO 5   (direct drive OK, HC-SR04 TRIG threshold tolerates 3.3V)
 *   HC-SR04 ECHO -> GPIO 18  *** VIA VOLTAGE DIVIDER ***
 *                   ECHO is a 5V logic output; ESP32 GPIOs are NOT 5V tolerant.
 *                   Use a divider: ECHO --[1k]-- GPIO18 --[2k]-- GND
 *                   (1k/2k drops ~5V to ~3.3V at the GPIO)
 *   SG90 signal  -> GPIO 13
 *   SG90 power   -> external 5V supply (or ESP32 5V/VIN rail) is strongly recommended;
 *                   the servo's current spikes (~100-250 mA) can brown out the board
 *                   if powered from the 3.3V regulator. Share GND with the ESP32.
 *
 * Required libraries (Arduino Library Manager):
 *   - ESP32Servo            (Kevin Harrington / Dlloydev)
 *   - ESPAsyncWebServer      (search "ESPAsyncWebServer"; if not found, see
 *                              https://github.com/ESP32Async/ESPAsyncWebServer)
 *   - AsyncTCP               (search "AsyncTCP"; if not found, see
 *                              https://github.com/ESP32Async/AsyncTCP)
 *
 * Behavior:
 *   - Servo sweeps 0..180 degrees and back, pausing briefly at each step to
 *     take an HC-SR04 reading.
 *   - Every (angle, distance) reading is broadcast to all connected WebSocket
 *     clients as a compact JSON message: {"a":<angle_deg>,"d":<distance_cm>|null}
 *   - The served webpage renders a dark "radar scope" style SVG: range rings,
 *     a rotating sweep line, fading blips at each detection, and a continuous
 *     SVG <path> tracing the boundary of the most recent readings at every angle.
 *
 * Network:
 *   - Tries to join your WiFi (STA mode) using STA_SSID/STA_PASS below.
 *   - If that fails within STA_TIMEOUT_MS, it falls back to its own access
 *     point (AP_SSID/AP_PASS) so you can connect directly to the ESP32.
 *   - Once connected, open a browser to the printed IP address (port 80).
 *
 * Customization:
 *   - SWEEP_STEP_DEG, STEP_INTERVAL_MS, SERVO_SETTLE_MS control sweep speed/resolution.
 *     If you change SWEEP_STEP_DEG, also update NUM_STEPS/STEP in the embedded JS below
 *     to match (NUM_STEPS = 180/SWEEP_STEP_DEG + 1).
 * =====================================================================================
 */

#include <WiFi.h>
#include <ESPAsyncWebServer.h>
#include <AsyncTCP.h>
#include <ESP32Servo.h>
#include "index.h" //This file contains the Webpage HTML and JavaScript code
// Setup OLED Onboard Display
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels

#define OLED_RESET -1
// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

// ----------------------------- WiFi configuration -------------------------------------
const char* STA_SSID = "IC-STEM-AP";
const char* STA_PASS = "awtfp@ICSTEM";
const unsigned long STA_TIMEOUT_MS = 10000;

const char* AP_SSID = "ESP32-Radar";
const char* AP_PASS = "radar1234"; // must be >= 8 characters

// ----------------------------- Pin assignments -----------------------------------------
const int TRIG_PIN  = 12;
const int ECHO_PIN  = 13;  // through voltage divider, see wiring notes above
const int SERVO_PIN = 14;

// ----------------------------- Sweep configuration --------------------------------------
const int SWEEP_MIN_DEG       = 0;
const int SWEEP_MAX_DEG       = 180;
const int SWEEP_STEP_DEG      = 2;     // must match STEP in the JS below
const unsigned long SERVO_SETTLE_MS  = 40;  // time given to the servo to reach position
const unsigned long STEP_INTERVAL_MS = 100;  // total time budget per angle step

int sweepAngle = SWEEP_MIN_DEG;
int sweepDir   = 1;
unsigned long lastStepTime = 0;

Servo panServo;

// ----------------------------- Web server / WebSocket ------------------------------------
AsyncWebServer server(80);
AsyncWebSocket ws("/ws");

// ----------------------------- HC-SR04 measurement ----------------------------------------
float measureDistanceCM() {
  digitalWrite(TRIG_PIN, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIG_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);

  // 30 ms timeout ~= 5 m round trip; well beyond the HC-SR04's ~4 m spec
  unsigned long duration = pulseIn(ECHO_PIN, HIGH, 30000UL);
  if (duration == 0) return -1.0f;  // timeout / no echo

  float distanceCM = duration * 0.0343f / 2.0f;
  if (distanceCM < 2.0f || distanceCM > 400.0f) return -1.0f; // outside sensor spec
  return distanceCM;
}

void broadcastReading(int angleDeg, float distanceCM) {
  Serial.printf("angle=%3d  distance=%s\n", angleDeg,
                distanceCM < 0 ? "out of range" : String(distanceCM, 1).c_str());
    // Display static text
//  display.clearDisplay();
  display.setCursor(5,5);
  display.println("ScanningSonar Server");
  display.println("");
  display.println(WiFi.softAPIP());
  display.println(WiFi.localIP());
  display.display();

  if (ws.count() == 0) return; // nobody listening, skip the work

  char buf[48];
  if (distanceCM < 0) {
    snprintf(buf, sizeof(buf), "{\"a\":%d,\"d\":null}", angleDeg);
  } else {
    snprintf(buf, sizeof(buf), "{\"a\":%d,\"d\":%.1f}", angleDeg, distanceCM);
  }
  ws.textAll(buf);
}

// ----------------------------- WebSocket event handler -------------------------------------
void onWsEvent(AsyncWebSocket *server, AsyncWebSocketClient *client,
               AwsEventType type, void *arg, uint8_t *data, size_t len) {
  if (type == WS_EVT_CONNECT) {
    Serial.printf("WebSocket client #%u connected from %s\n",
                  client->id(), client->remoteIP().toString().c_str());
  } else if (type == WS_EVT_DISCONNECT) {
    Serial.printf("WebSocket client #%u disconnected\n", client->id());
  }
}


// ----------------------------- Setup / Loop -------------------------------------------------
bool connectSTA(unsigned long timeoutMs) {
  WiFi.mode(WIFI_STA);
  WiFi.begin(STA_SSID, STA_PASS);
  unsigned long start = millis();
  Serial.print("Connecting to WiFi");
  while (WiFi.status() != WL_CONNECTED && millis() - start < timeoutMs) {
    delay(250);
    Serial.print(".");
  }
  Serial.println();
  return WiFi.status() == WL_CONNECTED;
}

void startAP() {
  WiFi.mode(WIFI_AP);
  WiFi.softAP(AP_SSID, AP_PASS);
  Serial.print("AP started. SSID: ");
  Serial.print(AP_SSID);
  Serial.print("  IP: ");
  Serial.println(WiFi.softAPIP());
}

void setup() {
  Serial.begin(115200);
  delay(300);

// Initialize OLED Display
  Wire.begin(21, 22); // SDA=21, SCL=22
  if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // Address 0x3D for 128x64
    Serial.println(F("SSD1306 allocation failed"));
    for(;;);
  }
  delay(2000);
  display.clearDisplay();
  display.setTextColor(WHITE);
  display.setTextSize(1);
//  display.setCursor(15, 10);
//  display.print("Hello, world!");
//  display.display();

// Initialize Ultrasonic Sensor
  pinMode(TRIG_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);
  digitalWrite(TRIG_PIN, LOW);

// Initialize Servo
  ESP32PWM::allocateTimer(0);
  panServo.setPeriodHertz(50);
  panServo.attach(SERVO_PIN, 490, 2555); // for wider scan
  panServo.write(SWEEP_MIN_DEG);
  delay(400); // let the servo reach the start position before sweeping

// Initialize Network
  if (connectSTA(STA_TIMEOUT_MS)) {
    Serial.print("WiFi connected. IP: ");
    Serial.println(WiFi.localIP());
  } else {
    Serial.println("STA connect failed, falling back to AP mode.");
    startAP();
  }

// Initialize WebSocket Server
  ws.onEvent(onWsEvent);
  server.addHandler(&ws);

  server.on("/", HTTP_GET, [](AsyncWebServerRequest *request) {
    request->send_P(200, "text/html", INDEX_HTML);
  });
  server.onNotFound([](AsyncWebServerRequest *request) {
    request->send(404, "text/plain", "Not found");
  });

  server.begin();
  Serial.println("HTTP server started.");
}

// Execute Scan Processing
void loop() {
  unsigned long now = millis();
  if (now - lastStepTime >= STEP_INTERVAL_MS) {
    lastStepTime = now;

    panServo.write(sweepAngle);
    delay(SERVO_SETTLE_MS);

    float distanceCM = measureDistanceCM();
    broadcastReading(sweepAngle, distanceCM);

    sweepAngle += sweepDir * SWEEP_STEP_DEG;
    if (sweepAngle >= SWEEP_MAX_DEG) { sweepAngle = SWEEP_MAX_DEG; sweepDir = -1; }
    else if (sweepAngle <= SWEEP_MIN_DEG) { sweepAngle = SWEEP_MIN_DEG; sweepDir = 1; }
  }

  ws.cleanupClients();
}