使用Express JS服务器和Johnny-Five控制Arduino

时间:2018-05-07 18:07:13

标签: reactjs express arduino johnny-five

我想从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");
});

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

1 个答案:

答案 0 :(得分: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);

以上是未经测试的,但如果您找到了解决方案,请发布解决方案!