I've been immersed in a fascinating Arduino project lately. This project involves the Arduino communicating with a NodeJS server via serialport, while the server sends data to the client through socket.io.
One milestone I've achieved is getting real-time information to appear in the browser using the h1 tag as a counter for the Arduino.
The issue I'm facing now is that the counter only updates when I manually refresh the browser. My ultimate goal is to have this information update automatically without any user intervention. Unfortunately, after scouring through the documentation, I couldn't find any relevant events in socket.io that would facilitate this automatic update.
Here's a snippet of my code:
index.js
const express = require('express');
const app = express();
const http = require('http').createServer(app);
app.use(express.static(__dirname + '/public'));
let expressPort = process.env.PORT || 3000;
// Socket:
const io = require('socket.io')(http);
// Arduino Stuff:
const SerialPort = require('serialport');
const ReadLine = SerialPort.parsers.Readline;
const port = new SerialPort('COM3', { baudRate: 9600 });
const parser = port.pipe(new ReadLine({ delimiter: '\r\n' }));
parser.on('data', data => {
let counter = data;
console.log(counter);
io.on('connection', socket => {
io.emit('arduino', counter);
});
});
parser.on('error', error=> {
console.log(error);
});
// Express stuff
app.use(express.static(__dirname + '/public'));
app.get('/', (req, res) => {
res.sendFile(__dirname + '/public/');
});
http.listen(expressPort, () => {
console.log(`Listening on port: ${expressPort}`);
});
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Arduino Stuff</title>
</head>
<body>
<h1 id="counter"></h1>
<script src="/socket.io/socket.io.js"></script>
<script src="app.js" charset="UTF-8"></script>
</body>
app.js
const socket = io();
socket.on('arduino', data => {
console.log(data);
const counter = document.getElementById('counter');
counter.innerHTML = data;
});
Your assistance in resolving this issue would be truly appreciated :)
EDIT:
I unintentionally omitted the Arduino code, but essentially it's a simple counter with a delay:
int counter = 0;
void setup() {
Serial.begin(9600);
}
void loop() {
Serial.println(++counter, DEC);
delay(3000);
}