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