2

我想从 Web 界面控制我的 Arduino,所以我在 ReactJS 中创建了客户端,在 ExpressJS 中创建了服务器端(包括 Johnny-Five)。

我只想根据用户输入实时更新闪烁 LED 的间隔。这是我的服务器代码:

const express = require('express');
const bodyParser = require('body-parser');
const five = require('johnny-five');

const app = express();
const board = new five.Board();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

board.on('ready', function () {
  app.post("/api/led-flash", function (req, res) {
    let led = new five.Led(13);
    led.blink(req.body.interval);
  });
});

app.listen("5000", () => {
  console.log("App listening on port 5000");
});

该代码似乎只适用于一开始的几个请求。这样做的正确方法是什么?

4

1 回答 1

1

您需要在开发板准备好后启动服务器。所以类似于以下内容:

const express = require('express');
const bodyParser = require('body-parser');
const five = require('johnny-five');

const app = express();
const board = new five.Board();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.post("/api/led-flash", function (req, res) {
    // perform some initial cleanup work if needed like resetting LEDs.
    // ...


    let led = new five.Led(13);
    led.blink(req.body.interval);

    res.json({ message: 'success!'})

    // Some additional work after success
    // ...
});

function startServer() {
    app.listen("5000", () => {
        console.log("App listening on port 5000");
    });
}

board.on('ready', startServer);

以上内容未经测试,但如果找到解决方案,请发布解决方案!

于 2018-05-07T18:18:53.100 回答