【问题标题】:How to auto update a socket.io with arduino?如何使用arduino自动更新socket.io?
【发布时间】:2021-02-27 08:50:23
【问题描述】:

我目前正在做一个 arduino 项目。 arduino 是否通过串行端口与 NodeJS 服务器通信,服务器是否通过 socket.io 向客户端发送数据

我已经获得了要显示在浏览器中的信息(带有 arduino 的“实时”计数器的 h1 标签)。

问题是要更新计数器,我必须刷新浏览器。我的目标是确保这些信息自动更新。我查看了文档,没有找到任何涉及更新的 socket.io 事件。

这是我的代码:

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

提前非常感谢你:)

编辑:

我忘了放arduino代码,但基本上它只是一个带有delay的计数器:

int counter = 0;

void setup() {
  Serial.begin(9600);
}

void loop() {
  Serial.println(++counter, DEC);
  delay(3000);
}

【问题讨论】:

    标签: javascript express socket.io arduino serial-communication


    【解决方案1】:

    好吧,我很愚蠢,只是不要用 io.on('connection'...) 包装 de emit 方法, 本身没有“更新”方法, emit 方法足以实现这一点,但是,如果你将它插入到“连接”中,那么它只是在第一个连接中调用,ergo,只是在刷新中显示信息。

    结果:

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

    对不起,浪费了你们的时间,伙计们:(

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-15
      • 1970-01-01
      • 2021-01-15
      • 1970-01-01
      • 1970-01-01
      • 2018-04-29
      • 2018-10-02
      相关资源
      最近更新 更多