Search code examples
javascriptnode.jsplotlymicrocontrollermsp432

Using Plotly.js and Node.js to get and plot data


I'm trying to create a simple webpage which gets data from a microcontroller (MSP432) and plots it on a graph in real time.

I have researched and I'm currently using plotly.js and html to create the graph. I currently have a graph that updates itself with random data in realtime.

I have attached the code for the page below.

I now want to stream the data in, and I have looked at node.js and in particular the serialport library. I think I have installed the serialport npm.

The part where I'm confused is how does the node.js code fit in with my html/plotlyjs index file?

I have never used javascript before. It's my first time with nodejs especially, so I'm confused. Should I just put it inside the <script> tag right in the getX() getY() function?

Also does anyone know how I can go about starting the nodejs code? I'm kind of lost.

This is my index.html file:

     <!DOCTYPE html>

     <html lang="en" xmlns="http://www.w3.org/1999/xhtml">
     <head>
         <script src="plotly.min.js"></script>
         <meta charset="utf-8" />
         <title>My Plot Page</title>
    </head>
    <body>
         <p>Plotly plot:</p>
         <div id="chart1"></div>
         <script>
            var counter = 0;
            function getX() {
             counter++;
             return counter;
            }
            function getY() {
             return Math.random();
            }
            Plotly.plot('chart1', [{
             x: [getX()],
             y: [getY()],
             type: 'line'
            }]);
            setInterval(function () {
              Plotly.extendTraces('chart1', { x: [[getX()]] , y: [[getY()]] }, [0])
    }, 200);
         </script>
    </body>
    </html>

Solution

  • Node.js is an open source server environment. It is used to host a webserver and can't be run inside the webbrowser. It can be used to read serial port data and send it to the connected clients.

    An example setup would be as below:

    ---------------------------------------------------------------------------
    | MSP432              node.js server                  web page in browser |
    |   M <==================>  N  <===========================>  W           |
    |           serial                       websockets                       |
    ---------------------------------------------------------------------------
    

    The nodejs server (N) reads the data from the serial port and manages the MSP432 (M). The server (N) also hosts a webserver (using expressjs) and opens a websocket with the connected webpage (W) to transfer new data. An easy to use websocket library is socket.io.

    A simple nodejs webserver can be created by doing:

    express --view=pug <your application name>
    

    please note that ejs can also be used instead of pug

    ajax can also be used instead of websockets