Hi All,
I am trying to get my project working which is a parking system using a V53L1X Lidar sensor and I have it working on a webpage, see attached pic.
But the software I want to interface with the developer has asked for other ways to read the info so I started with websockets and json output
I have followed plenty of online tutorials but found this
By ACROBOTIC which was closer to what I wanted minus the graphical output
I have modified the code which compiles without an issue and uploads to my esp8266 D1 clone with no problem, serial monitor is showing my sensor data too.
The only issue I have is that I can not get the data to send through WebSocketserver.
Any help appreciated.
// Load Wi-Fi library
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <Wire.h>
#include <VL53L1X.h>
#include <WebSocketsServer.h>
int distance;
VL53L1X sensor;
ESP8266WebServer server;
WebSocketsServer webSocket = WebSocketsServer(81);
// Replace with your network credentials
const char* ssid = "SCANPORT-WIRE";
const char* password = "SK@nP0rt*";
char webpage[] PROGMEM = R"=====(
<html>
<body onload="javascript:init()">
<div>
<canvas id="line-chart" width="800" height="450"></canvas>
</div>
<!-- Adding a websocket to the client (webpage) -->
<script>
var webSocket;
function init() {
webSocket = new WebSocket('ws://' + window.location.hostname + ':81/');
webSocket.onmessage = function(event) {
var data = JSON.parse(event.data);
console.log(data);
}
}
</script>
</body>
</html>
)=====";
void setup() {
Serial.begin(115200);
Wire.begin(); //SDA, SCL
Wire.setClock(400000); // use 400 kHz I2C
sensor.setTimeout(500);
if (!sensor.init())
{
Serial.println("Failed to detect and initialize sensor!");
while (1);
}
sensor.setDistanceMode(VL53L1X::Long);
sensor.setMeasurementTimingBudget(50000);
sensor.startContinuous(50);
// Connect to Wi-Fi network with SSID and password
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
// Print local IP address and start web server
Serial.println("");
Serial.println("WiFi connected.");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
server.on("/",[](){
server.send_P(200, "text/html", webpage);
});
server.begin();
webSocket.begin();
webSocket.onEvent(webSocketEvent);
}
void loop() {
webSocket.loop();
server.handleClient();
distance = sensor.read() / 10;
Serial.println(distance);
delay(3000);
}
void getData() {
//Serial.println(sensor.read());
String json = "{\"value\":";
json += sensor.read();
json += "}";
webSocket.broadcastTXT(json.c_str(), json.length());
}
void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t lenght){
}