使用javascript和socket.io从串行端口显示多个传感器数据

时间:2018-09-25 04:03:01

标签: node.js express charts socket.io arduino

我是Node.JS和Arduino的新手。我有一个带有温度传感器的Arduino装置。我正在用Arduino读取温度值。我的串行监视器输出如下:

  

串行监视器:

0.05
0.10
0.15
0.20
0.25
0.30
0.34

我通过串行端口将数据从Arduino发送到我的终端,然后以图表形式在Web浏览器上显示数据。我正在使用express和socket.io。 这是与arduino和带有index.js的浏览器的连接。还有index.html

  

index.js:


    var express = require('express');

    var app = express();
    var http = require('http').Server(app);
    var server = http.listen(4000, "0.0.0.0", () => { //Start the server, listening on port 4000.
        console.log("Listening to requests on port 4000...");
    })

    var io = require('socket.io')(server); //Bind socket.io to our express server.

    app.use(express.static('public')); //Send index.html page on GET /

    const SerialPort = require('serialport');
    const Readline = SerialPort.parsers.Readline;
    const port = new SerialPort('/dev/ttyUSB0'); //Connect serial port to port COM3. Because my Arduino Board is connected on port COM3. See yours on Arduino IDE -> Tools -> Port
    const parser = port.pipe(new Readline({delimiter: '\r\n'})); //Read the line only when new line comes.
    parser.on('data', (temp) => { //Read data
        console.log(temp);
        var today = new Date();
        io.sockets.emit('temp', {date: today.getDate()+"-"+today.getMonth()+1+"-"+today.getFullYear(), time: (today.getHours())+":"+(today.getMinutes()), temp:temp}); //emit the datd i.e. {date, time, temp} to all the connected clients.
    });

    io.on('connection', (socket) => {
        console.log("Someone connected."); //show a log as a new client connects.
    })

从Arduino串行端口接收的温度数据显示在index.html(网络浏览器)中。

  

index.html:

<!DOCTYPE html>
<html>
    <head>
        <title>Temperature Plot</title>
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        <h1>Temperature Graph</h1>
        <h4>Date: <span id="date"></span></h4>
        <div class="chart-container" style="position: relative; width:75vw; margin: auto;">
            <canvas id="myChart"></canvas>
        </div>
        <link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet">
        <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.4.0/Chart.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.4/socket.io.js"></script>
        <script>
            var socket = io.connect('http://192.168.1.3:4000'); //connect to server
            var ctx = document.getElementById('myChart').getContext('2d');
            var chart = new Chart(ctx, {
                // The type of chart we want to create
                type: 'line',
                // The data for our dataset
                data: {
                labels: [],
                datasets: [{
                    label: "Temperature",
                    borderColor: "#FF5733",
                    data: [],
                    fill: false,
                    pointStyle: 'circle',
                    backgroundColor: '#3498DB',
                    pointRadius: 5,
                    pointHoverRadius: 7,
                    lineTension: 0,
                }]
                },
                // Configuration options go here
                options: {}

            });
            socket.on('temp', function(data) { //As a temp data is received
                console.log(data.temp);
                document.getElementById('date').innerHTML = data.date; //update the date
                if(chart.data.labels.length != 15) { //If we have less than 15 data points in the graph
                    chart.data.labels.push(data.time);  //Add time in x-asix
                    chart.data.datasets.forEach((dataset) => {
                        dataset.data.push(data.temp); //Add temp in y-axis
                    });
                }
                else { //If there are already 15 data points in the graph.
                    chart.data.labels.shift(); //Remove first time data
                    chart.data.labels.push(data.time); //Insert latest time data
                    chart.data.datasets.forEach((dataset) => {
                        dataset.data.shift(); //Remove first temp data
                        dataset.data.push(data.temp); //Insert latest temp data
                    });
                }
                chart.update(); //Update the graph.
            });
        </script>
    </body>
    <style>
        h1 {
            text-align: center;
            font-family: 'Lato', sans-serif;
        }
        h4 {
            text-align: center;
            font-family: 'Lato', sans-serif;
        }
        p {
            text-align: center;
            font-family: 'Lato', sans-serif;
        }
    </style>
</html>

如果Arduino上只有1个传感器温度,那么一切都可以正常工作,但是当我添加另一个具有如下所示的串行监视器结果的温度传感器时,使传感器数据无法以index.html和控制台的图表形式出现浏览器还只显示与串行监视器相同的数据。

  

带有2个温度传感器的串行监视器(温度传感器之间的读数结果之间用空格隔开)

0.05 1.00
0.10 1.00
0.15 0.99
0.20 0.98
0.25 0.97
0.30 0.96
0.34 0.94

我已经尝试解决了近一个星期的问题,我尝试了多种方法来解决此问题,但是它没有用,我确实需要您的帮助

  

arduino代码:

double x; //I simulate 2 temperature sensor values
    void setup() {
      Serial.begin(115200);
      x = 0;
    }

    void loop() {  
      Serial.print(sin(x));
      Serial.print(" ");
      Serial.println(cos(x));
      delay(50);

      // seting batasan input fungsi sinus
      x += 0.05;
      if(x>= 2*3.14){
        x = 0;
      }  
    }

1 个答案:

答案 0 :(得分:1)

其中基本上有两个问题。

  1. 如何格式化数据并使用express服务器并将其发送到前端
  2. 如何使用chart.js在图形中显示多个数据集

第1次

代码行

...
const parser = port.pipe(new Readline({delimiter: '\r\n'}));
...

实际上捕获每行数据。但是,由于arduino的输出在同一行中包含数据,因此我们必须在split()字符处space。因此,要获得多个温度值的array,可以使用tempArray = temp.split(" ");。然后可以将此数组发送到前端。

第二次

获得温度值数组后,可以使用

将数组本身发送到前端
// Notice I have replaced `temp` with `tempArray`
io.sockets.emit('temp', {date:today.getDate()+"-"+today.getMonth()+1+"-"+today.getFullYear(), time: (today.getHours())+":"+(today.getMinutes()), temp:tempArray}); });

在前端,dataset对象中的Chart是一个数组。而且,如果您想向图表添加多个数据集,则只需添加一个数据集对象即可添加它们:

....
datasets: [{
           label: "Sensor1",
           borderColor: "#FF5733",
           data: [],
           fill: false,
           pointStyle: 'circle',
           backgroundColor: '#3498DB',
           pointRadius: 5,
           pointHoverRadius: 7,
           lineTension: 0,
          },
....
....

          {
           label: "Sensor2",
           borderColor: "#FFFF33",
           data: [],
           fill: false,
           pointStyle: 'circle',
           backgroundColor: '#34FFDB',
           pointRadius: 5,
           pointHoverRadius: 7,
           lineTension: 0,
          },
]
....

现在,在socket.on('temp', function(data){...})内部,您可以像这样推送数据:

chart.dataset[i].data.push(data.temp[i]) // looping over i

编辑

要将数据放入数据集中,可以使用“ for”循环,如下所示:

for (var i = 0; i < datasets.length; i++) {
    chart.datasets[i].data.push(data.temp[i]);
}