Esp32 not sending data through the webscket[SOLVED]

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Angle-Distance Chart</title>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
      body {
        font-family: Arial, sans-serif;
        display: flex;
        justify-content: center;
        align-items: center;
        height: 100vh;
        margin: 0;
        background-color: #f8f9fa;
      }
      #chartContainer {
        width: 80%;
        max-width: 800px;
      }
      canvas {
        width: 100% !important;
        height: 400px !important;
      }
    </style>
  </head>
  <body>
    <div id="chartContainer">
      <canvas id="chartCanvas"></canvas>
    </div>

    <script>
      // Sanity check to make sure JS is running
      console.log("๐Ÿงช JS is running!");

      const socket = new WebSocket("ws://192.168.27.51:8080");

      // Timeout warning if WebSocket connection isn't established in time
      setTimeout(() => {
        if (socket.readyState !== WebSocket.OPEN) {
          console.warn("โณ Still waiting for WebSocket connection...");
        }
      }, 3000);

      socket.onopen = () => {
        console.log("โœ… Connected to ESP32 WebSocket!");
        socket.send("hello from browser");
      };

      socket.onmessage = (event) => {
        console.log("๐Ÿ“ฉ Raw message from ESP32:", event.data);

        try {
          const data = JSON.parse(event.data);
          console.log("โœ… Parsed JSON:", data);

          if (data.angle !== undefined && data.distance !== undefined) {
            const angle = parseInt(data.angle);
            const distance = parseFloat(data.distance);

            console.log(
              `๐Ÿ“ˆ Updating graph โ†’ Angle: ${angle}, Distance: ${distance}`
            );
            console.log(
              `๐Ÿงช Types โ†’ angle: ${typeof angle}, distance: ${typeof distance}`
            );

            updateGraph(angle, distance);
          } else {
            console.warn("โš ๏ธ JSON missing angle or distance:", data);
          }
        } catch (error) {
          console.error("๐Ÿšจ JSON Parse Error:", error);
        }
      };

      socket.onerror = (error) => {
        console.error("๐Ÿšจ WebSocket Error:", error);
      };

      socket.onclose = () => {
        console.warn("๐Ÿ”ด WebSocket Disconnected");
      };

      // Chart.js setup
      const ctx = document.getElementById("chartCanvas").getContext("2d");
      const chartData = {
        labels: [],
        datasets: [
          {
            label: "Distance (cm)",
            borderColor: "#17a2b8",
            backgroundColor: "rgba(23, 162, 184, 0.2)",
            data: [],
            fill: true,
          },
        ],
      };

      const chartOptions = {
        scales: {
          x: { title: { display: true, text: "Angle (degrees)" } },
          y: {
            title: { display: true, text: "Distance (cm)" },
            min: 0,
            max: 200,
          },
        },
      };

      const chart = new Chart(ctx, {
        type: "line",
        data: chartData,
        options: chartOptions,
      });

      function updateGraph(angle, distance) {
        console.log("๐Ÿงฉ Current Labels:", chartData.labels);

        const index = chartData.labels.indexOf(angle);

        if (index === -1) {
          console.log(`โž• Adding new angle: ${angle}`);
          chartData.labels.push(angle);
          chartData.datasets[0].data.push(distance);
        } else {
          console.log(`๐Ÿ” Updating existing angle at index ${index}`);
          chartData.datasets[0].data[index] = distance;
        }

        chart.update();
      }
    </script>
  </body>
</html>

#include <ESP32Servo.h>
#include <WiFi.h>
#include <WebSocketsServer.h>
 
#define TRIG_PIN 32
#define ECHO_PIN 33
#define SERVO_PIN 18
#define BUZZER_PIN 15
 
const char* ssid = "Galaxy A12 306F";
const char* password = "vhgl3899";
 
Servo myServo;
WebSocketsServer webSocket(8080);
float distanceArray[181] = {0};
 
void setup() {
    Serial.begin(115200);
    WiFi.begin(ssid, password);

    // โœ… Set pin modes
    pinMode(TRIG_PIN, OUTPUT);
    pinMode(ECHO_PIN, INPUT);

    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
    }

    Serial.println("\nโœ… WiFi connected");
    Serial.print("๐Ÿ“ก ESP32 IP Address: ");
    Serial.println(WiFi.localIP());

    webSocket.begin();
    Serial.println("๐ŸŸข WebSocket server started on port 8080");

    webSocket.onEvent([](uint8_t num, WStype_t type, uint8_t * payload, size_t length) {
        Serial.println("๐Ÿ“ฉ WebSocket Event Triggered!");

        if (type == WStype_TEXT) {
            Serial.print("๐Ÿ“จ Message received: ");
            Serial.println((char*)payload);

            if (strcmp((char*)payload, "hello from browser") == 0) {
                webSocket.sendTXT(num, "hello from ESP");
                Serial.println("๐Ÿ“ค Sent reply: hello from ESP");
            }
        }
    });

    myServo.setPeriodHertz(50);
    myServo.attach(SERVO_PIN, 1000, 2000);
    myServo.write(90);

    Serial.println("๐Ÿ”„ Testing Servo...");
    myServo.write(0);
    delay(1000);
    myServo.write(180);
    delay(1000);
    myServo.write(90);
}

float getDistance() {
    // ๐Ÿ›  Ensure stable sensor signal
    digitalWrite(TRIG_PIN, LOW);
    delayMicroseconds(5);

    digitalWrite(TRIG_PIN, HIGH);
    delayMicroseconds(10);

    digitalWrite(TRIG_PIN, LOW);

    // โฑ Increase timeout a bit more
    long duration = pulseIn(ECHO_PIN, HIGH, 150000);  // 150ms

    if (duration == 0) {
        Serial.println("โš ๏ธ Sensor timeout (no echo)");
        return -1;
    }

    float distance = duration * 0.0343 / 2;

    if (distance < 2 || distance > 400) {
        Serial.println("โš ๏ธ Invalid distance (out of range)");
        return -1;
    }

    return distance;
}
 
void loop() {
    webSocket.loop();
    float newDistanceArray[181] = {0};
 
    for (int pos = 0; pos <= 180; pos += 5) {
        myServo.write(pos);
        delay(300);
 
        float dist = getDistance();
        if (dist != -1) {
            newDistanceArray[pos] = dist;
            sendWebData(pos, dist);
        }
    }
 
    for (int pos = 180; pos >= 0; pos -= 5) {
        myServo.write(pos);
        delay(300);
 
        float dist = getDistance();
        if (dist != -1) {
            newDistanceArray[pos] = dist;
            sendWebData(pos, dist);
        }
    }
 
    memcpy(distanceArray, newDistanceArray, sizeof(distanceArray));
    delay(2000);  // Wait before next full sweep
}
 
void sendWebData(int angle, float distance) {
    String message = "{\"angle\": " + String(angle) + ", \"distance\": " + String(distance) + "}";
    Serial.println("๐Ÿ“ค Sending data: " + message);
    webSocket.broadcastTXT(message);
}

outputs in the serial monitor: :white_check_mark: WiFi connected
:satellite_antenna: ESP32 IP Address: 192.168.27.51
:green_circle: WebSocket server started on port 8080
:counterclockwise_arrows_button: Testing Servo...
:outbox_tray: Sending data: {"angle": 0, "distance": 13.98}
:outbox_tray: Sending data: {"angle": 5, "distance": 13.98}
outputs in the browser:":hourglass_not_done: Still waiting for WebSocket connection...

did anyone have a similar problem?

Hello,

Please edit your code to correct the way you used the code tags
It's hard like this to read your code

If you chart js is trying to connect to port 8080 then it will be waiting a long time as the server...

ESP32 IP Address: 192.168.27.51
WebSocket server started on port 8081

errors in the post fixed, should be readable now

I merged your topics @ariealzeev. It is not appropriate to create a new topic to make changes requested by the forum helpers.

In cases where you want to make a change to an existing post that does not change the informational content of the post, as is the case with the requested formatting fix, you can just edit your post:

  1. Click the icon that looks like a pencil (๐Ÿ–‰) at the bottom of the post you want to edit.
    The post composer will open, populated with the content of the existing post.
  2. Make the desired changes to the post content.
  3. Review the rendered post preview panel at the right side of the post composer to verify that it is all correct.
    โ“˜ The preview panel is also used by the forum software to show you messages related to posting, so if you see messages to the right of the composer instead of the preview, just carefully read the messages and then close them by clicking the X icon at the top right of the message to see the preview.
  4. Click the "Save edit" button at the bottom of the post composer.

:red_exclamation_mark: Edits should not be used in cases where you want to make additions or corrections to a post which changes its informational content.


In cases where you want to add, clarify, or correct the informational content of a post, do that by adding a new reply on the forum topic. This way, the participants in the discussion will see the new information. If you instead used an edit for the purpose then the participants would not notice it, which will result in confusion, frustration, and make it less likely for you to get the help you need.

solved, the problem was the delay(). working code:

// esp32_websocket_scan.cpp โ€“ always emitting frames (distance = -1 when no echo)
// -----------------------------------------------------------------------------
// Libraries: ESP32Servo (John Bennett), WebSockets (Links2004)
// -----------------------------------------------------------------------------
#include <WiFi.h>
#include <WebSocketsServer.h>
#include <ESP32Servo.h>
 
// ===== Wiโ€‘Fi credentials =====
const char* WIFI_SSID     = "";
const char* WIFI_PASSWORD = "";
 
// ===== Pins =====
static const uint8_t SERVO_PIN = 18;  // PWM
static const uint8_t TRIG_PIN  = 32;
static const uint8_t ECHO_PIN  = 33;
 
// ===== Scan parameters =====
static const uint16_t STEP_DEG         = 5;
static const uint32_t STEP_INTERVAL_MS = 300;
static const uint16_t PULSE_TIMEOUT_US = 25'000; // 4 m
 
WebSocketsServer ws(8080);
Servo servo;
 
uint8_t  curAngle = 0;
bool     forward  = true;
uint32_t lastStep = 0;
 
// -----------------------------------------------------------------------------
float measureCM() {
  digitalWrite(TRIG_PIN, LOW); delayMicroseconds(2);
  digitalWrite(TRIG_PIN, HIGH); delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);
  long dur = pulseIn(ECHO_PIN, HIGH, PULSE_TIMEOUT_US);
  if (dur == 0) return -1.0f;                 // timeout โ†’ no echo
  return dur * 0.0343f / 2.0f;                // cm
}
 
void sendFrame(uint8_t angle, float distance) {
  String msg = "{\"angle\":" + String(angle) + ",\"distance\":" + String(distance, 1) + "}";
  ws.broadcastTXT(msg);
}
 
void onWs(uint8_t num, WStype_t type, uint8_t*, size_t) {
  if (type == WStype_CONNECTED) {
    Serial.printf("[WS] Client %u connected\n", num);
  }
}
 
void connectWiFi() {
  Serial.printf("[WiFi] Connecting to %s", WIFI_SSID);
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print('.'); }
  Serial.printf("\n[WiFi] %s\n", WiFi.localIP().toString().c_str());
}
 
void setup() {
  Serial.begin(115200);
  pinMode(TRIG_PIN, OUTPUT); pinMode(ECHO_PIN, INPUT);
  servo.attach(SERVO_PIN);
  connectWiFi();
  ws.begin(); ws.onEvent(onWs);
  servo.write(curAngle);
  lastStep = millis();
}
 
void loop() {
  ws.loop(); yield();
  uint32_t now = millis();
  if (now - lastStep >= STEP_INTERVAL_MS) {
    // update angle
    if (forward) {
      curAngle += STEP_DEG; if (curAngle >= 180) { curAngle = 180; forward = false; }
    } else {
      if (curAngle >= STEP_DEG) curAngle -= STEP_DEG; else curAngle = 0;
      if (curAngle == 0) forward = true;
    }
    servo.write(curAngle);
 
    // measure distance (may be -1)
    float d = measureCM();
    sendFrame(curAngle, d);    // ALWAYS send, even when d == -1
 
    lastStep = now;
  }
}

Well done. You then can set your topic as solved :slight_smile: