I am new to IoT so this question might sound a bit dumb but I am stuck and can't seem to figure out a solution. I am trying to send data from my mq-4 sensor to the node.js server. The code I have shows no error but I can't get any data to show on my front-end.
This is my Arduino IDE code:
#include <ESP8266WiFi.h>
#include <WebSocketsClient.h>
const char* ssid = "";
const char* password = "";
const char* webSocketServer = "IPAdress:8080";
WebSocketsClient webSocket;
void setup() {
Serial.begin(9600);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
webSocket.begin(webSocketServer, 8080);
}
void loop() {
int sensorValue = analogRead(A0);
String sensorValueStr = String(sensorValue);
webSocket.sendTXT(sensorValueStr);
webSocket.loop();
delay(1000);
}
I made sure that my server is connected to my front-end.
This is my server code:
const WebSocket = require('ws');
const http = require('http');
const fs = require('fs');
const server = http.createServer((req, res) => {
if (req.url === '/') {
res.writeHead(200, { 'Content-Type': 'text/html' });
const html = fs.readFileSync('index.html', 'utf8');
res.end(html);
} else {
res.writeHead(404);
res.end();
}
});
const wss = new WebSocket.Server({ server });
wss.on('connection', (ws) => {
ws.on('message', (message) => {
// Broadcast the actual sensor data to all connected clients
wss.clients.forEach((client) => {
if (client !== ws && client.readyState === WebSocket.OPEN) {
client.send(message);
}
});
});
});
server.listen(8080, () => {
console.log('Server is running on port 8080');
});
websocketsclient.handws