如何将带有传感器的初始化板导出为模块

How to export an initialized board with sensors as a module

作为一个基本示例,我有:

//tempModule.js
var five = require("johnny-five");
var board = new five.Board();
var temp;
board.on("ready", function() {
   temp = new five.Temperature({
pin: "A2",
controller: "AD8495"
   });
});
module.export = board;

调用者: //moduleTest.js

var board = require('tempModule.js');

setInterval(function(){
     console.log("Temp: " + board.temp);
  },500);

此代码当前正在返回 "undefined"。 我如何构造 tempModule.js 以便可以在另一个程序中使用来自连接到电路板的传感器的数据?

1.the 临时变量不是板的 属性,因此 board.temp 没有意义。

2.You没有导出临时文件,因此您无法访问它。

所以你需要像

一样导出临时文件
module.exports = temp;

或使用

exports.board = board; 
exports.temp = temp;

然后

var module = require('tempModule.js');

并使用

访问它
var board = module.board;
var temp = module.temp;

如果以上方法还是不行那还有一个办法

tempModule.js

var five = require("johnny-five"); 
var board = new five.Board();

function init(cb){
    board.on("ready", function() {
        var temp = new five.Temperature({ pin: "A2", controller: "AD8495" }); 
        cb(temp);
    });
}
exports.init = init;

并像这样使用它

var tempModule = require('tempModule.js');

tempModule.init(function (temp){
    temp.on("data", function() { 
        console.log(this.celsius + "°C", this.fahrenheit + "°F"); 
    });
});

更新:添加了另一个例子

// boardModule.js
var five = require("johnny-five"); 
var b = new five.Board();
var board = {};

function init(cb){
    b.on("ready", function() {
        board.temp1 = new five.Temperature({ pin: "A2", controller: "AD8495" }); 
        board.temp2 = new five.Temperature({ pin: "A3", controller: "AD8495" });
        board.temp3 = new five.Temperature({ pin: "A4", controller: "AD8495" }); 
        board.motor1 = new five.Motor({ pin: 5 });

        cb(board);
    });
}
exports.init = init;

// testModule.js
var boardModule = require('boardModule.js');

boardModule.init(function (board){

    board.temp1.on("data", function() { 
        console.log('temp1:', this.celsius + "°C", this.fahrenheit + "°F"); 
    });

    board.temp2.on("data", function() { 
        console.log('temp2:', this.celsius + "°C", this.fahrenheit + "°F"); 
    });

    board.temp3.on("data", function() { 
        console.log('temp3:', this.celsius + "°C", this.fahrenheit + "°F"); 
    });


    board.motor1.on("start", function() {
        console.log("start", Date.now());

        // Demonstrate motor stop in 2 seconds
        board.wait(2000, function() {
            board.motor1.stop();
        });
    });

    board.motor1.on("stop", function() {
        console.log("stop", Date.now());
    });

    board.motor1.start();
});