1

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

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

此代码当前返回“未定义”。如何构建 tempModule.js,以便可以在另一个程序中使用来自连接到板上的传感器的数据?

4

1 回答 1

2

1. temp 变量不是 board 的属性,所以 board.temp 没有意义。

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

所以你需要像这样导出温度

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();
});
于 2016-03-15T10:17:16.610 回答