diff --git a/examples/reed.js b/examples/reed.js new file mode 100644 index 0000000..a63d70e --- /dev/null +++ b/examples/reed.js @@ -0,0 +1,23 @@ +var arduino = require('../'); + +var board = new arduino.Board({ + debug: false +}); + +var reed = new arduino.Reed({ + board : board, + pin : 7, + emitInitState: true +}); + +reed.on('calibrated', function(err, date) { + console.log('calibrated'); + + this.on('reedopen', function(err, date) { + console.log('reedopen', this.state); + }); + + this.on('reedclose', function(err, date) { + console.log('reedclose'); + }); +}); diff --git a/index.js b/index.js index 3c55f8c..09f0816 100644 --- a/index.js +++ b/index.js @@ -8,5 +8,6 @@ module.exports = { Sensor: require('./lib/sensor'), Ping: require('./lib/ping'), PIR: require('./lib/pir'), - LCD: require('./lib/lcd') + LCD: require('./lib/lcd'), + Reed: require('./lib/reed') }; diff --git a/lib/reed.js b/lib/reed.js new file mode 100644 index 0000000..7cc3923 --- /dev/null +++ b/lib/reed.js @@ -0,0 +1,74 @@ +var events = require('events'), + util = require('util'); + +/* + * Main Reed constructor + * Process options + * Tell the board to set it up + */ +var Reed = function (options) { + if (!options || !options.board) { + throw new Error('Must supply required options to PIR'); + } + this.board = options.board; + this.pin = this.board.normalizePin(options.pin || 7); + this.state = null; + this.calibrated = false; + this.emitInitState = options.emitInitState; + + setInterval(function () { + this.board.digitalRead(this.pin); + }.bind(this), 200); + + this.board.on('data', function (message) { + var m = message.slice(0, -1).split('::'), + timestamp = new Date(), + err = null, + pin, data; + + if (!m.length) { + return; + } + + pin = m[0]; + data = m[1]; + + if (pin === this.pin) { + // If this is not a calibration event + if (this.state != null && this.state != +data) { + + // Update current state of reed instance + this.state = +data; + + // 'reedclose' event fired when reed is closed + if (data === '01') { + this.emit('reedclose', err, timestamp); + } + + // 'reedopen' event fired when reed is open + if (data === '00') { + this.emit('reedopen', err, timestamp); + } + } + + // 'calibrated' event + if (!this.calibrated) { + this.calibrated = true; + this.state = +data; + this.emit('calibrated', err, timestamp); + + if(this.emitInitState) { + if(data === '01') { + this.emit('reedclose', err, timestamp); + } else if(data === '00') { + this.emit('reedopen', err, timestamp); + } + } + } + } + }.bind(this)); +}; + +util.inherits(Reed, events.EventEmitter); + +module.exports = Reed;