Guide to setting up automatic updates on a socket.io connection using an Arduino

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);
}

Answer №1

Oops, my mistake! Avoid wrapping the emit method with io.on('connection'...). There is no 'update' method specifically, as the emit method can achieve the desired outcome. However, placing it within the 'connection' will only execute on the initial connection, resulting in the information being displayed only upon refresh.

Here's the corrected code snippet:

parser.on('data', data => {
    let counter = data;
    console.log(counter);

    io.emit('arduino', counter);

});

Apologies for any inconvenience caused!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Node.js "unexpected symbol error" (seeking assistance)

While working on my Discord bot, I encountered an unexpected token error in my code. This issue has happened to me before, but despite spending 2 hours trying to troubleshoot it, I couldn't find a solution. Below is a snippet of the problematic code. ...

Tips for enlarging the tree view when running protractor exams. Check out this code excerpt below:

I have a code snippet below that represents one item out of many, each distinguished by ng-reflect-index. I am trying to write a test case to expand these nodes individually using Protractor. However, I am facing an issue in expanding the node using Prot ...

The URL specified for the Django project could not be located when running on the httpd server

Hey there, this post may be a little lengthy but I appreciate your patience. Currently, I'm working on a Django project running on an apache2 server. In my index.html file, I have two images embedded in anchor tags: <a id="pop1" href="#"> <i ...

Find the hex code corresponding to the darkest color in the JSON response

I'm working with a json response that contains various vehicle objects, each with a hexcode value representing the color of the vehicle: [ { "name":"Ford", "hexCode": "4B1A1F"}, { "name":"BMW", "hexCode": "FFFFFF"}, { "name":"Fiat", "hexCode" ...

The error message "Type 'Observable<void>' cannot be assigned to type 'Observable<IComment[]>' in ngrx" is indicating a mismatch in types within ngrx

Recently, I've been diving into learning ngrx by following a guide. The code in the guide matches mine, but I encountered the following error: Type 'Observable<void>' is not assignable to type 'Observable<IComment[]>'. ...

Challenges arising from the rendering of main.js in Vue.js

Recently, I started working with Vue and am now faced with the task of maintaining a project. Main.js contains the routing structure: Main.js import Vue from 'vue' const app = new Vue({ el: '#app', data: { message: & ...

Sending a POST request will generate a new file, then a subsequent GET request can be made

Seeking assistance with a seemingly simple task. I want to set up a POST request in order to send JSON data. This data will then be saved into files and made available for user download. The scenario is that I'm developing an application where users ...

Guide to building a react-redux application with a Node server as the backend

Hey there! I'm looking to build a react-redux app with a node server as the backend. Is it feasible for the node server to serve the react-redux app instead of having react-redux run on one port and node on another? Any suggestions on how to kick thi ...

Populate a div using an HTML file with the help of AJAX

In my main HTML file, there is a div element: <div id="content"></div> Additionally, I have two other HTML files: login.html and signup.html. Furthermore, there is a navigation bar located at the top of the page. I am curious to know if it i ...

Changing the element tag and flipping escape characters in html entities

My control over the string source is limited, as I can only use html(). However, I am in need of cleaning up the chaos within the source, The goal is to remove all instances of <div class="page"></div>, while retaining its content. The challen ...

How can I use apps script to automatically remove old files from google drive that are over a month old?

Every week, I secure backups of my sheets to a backup folder using the following code. Now, I am looking for a way to automatically delete files older than 1 month from the backup folder. How can I add a script to accomplish this? Backup code (triggered w ...

What could be causing the issue with retrieving HTTP requests in Nest.js even after configuring the controller?

After the individual who departed from the company utilized Nest.js to create this server-side system. They established the auth.controller, auth.service, auth.module, auth-token, jwt.strategy, and jwt-payload, with everything properly configured. I verifi ...

Struggling to establish the default selection value in AngularJS

I am currently working on a project involving PHP and Angular. The values I need for a select ng-options are coming from a database. I am struggling to set a default value for the select component from the parameters. I have searched through various sites ...

Tips for preventing tiny separation lines from appearing above and below unordered list elements

I am attempting to utilize twitter bootstrap to create a select-option style list. How can I eliminate the thin separation lines above and below the list of items? Refer to the screenshot: https://i.sstatic.net/1khEE.png Below is the visible code snippe ...

What is the correct way to set the encoding for a server-side string?

As someone who is fairly new to web development, especially on the front end side, I am facing an issue with encoding. I am using python 2.7 and Flask for this project. Environment: Python 2.7, Flask The problem arises when I send json data to a server ...

Executing an AJAX request in the onsubmit event of a form results in the form submission proceeding even when return false is

I am facing an issue with a form that I intend to use only for an AJAX call. The AJAX call is triggered on submit in order to utilize the auto-check feature for required fields. Despite returning false on submit, the form still submits. Surprisingly, when ...

JavaScript FormData class does not recognize disabled and checked states on Bootstrap 5 switches

I am implementing a Bootstrap 5 switch input that I need to be mandatory, meaning it should be checked by default and not uncheckable. The official documentation suggests combining the attributes checked and disabled. However, it seems like the Javascrip ...

Is there a way to dynamically read an input's ID and insert its value into a text using jQuery?

My goal is to retrieve the value from the input field and display it in a P tag, with the value being dynamic. UPDATE: Whenever the update button is clicked, the value should replace the text below in the paragraph. input { display: block; margin-b ...

GLTF file: Error 404 - File could not be located

Working on loading a GLTF file and encountering a specific error: https://i.sstatic.net/EbovJ.png Curious as to why the file cannot be located and opened. Is it necessary to establish a local server for this process? After reviewing other examples online ...

Using jQuery to add and remove CSS classes on IE9 with Selenium

Hello, sorry for the generic question. We are currently automating our UI testing using Selenium Web Driver (v2.24.1) and everything is going smoothly except for IE9. One of the functionalities we are testing involves showing and hiding UI controls using ...