As a basic example, I have:
//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;
Which gets called by:
//moduleTest.js
var board = require('tempModule.js');
setInterval(function(){
console.log("Temp: " + board.temp);
},500);
This code is currently returning "undefined". How do I structure tempModule.js so that the data from the sensors attached to the board can be utilized in another program?
1.the temp variable is not property of board so board.temp doesn't make sense.
2.You're not exporting temp so you can't access it.
So you need to export temp like
module.exports = temp;
or use
exports.board = board;
exports.temp = temp;
then
var module = require('tempModule.js');
and access it using
var board = module.board;
var temp = module.temp;
If the above still doesn't work then there's another way
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;
and use it like this
var tempModule = require('tempModule.js');
tempModule.init(function (temp){
temp.on("data", function() {
console.log(this.celsius + "°C", this.fahrenheit + "°F");
});
});
Update: Added another example
// 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();
});