forked from ecto/duino
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsensor.js
More file actions
45 lines (37 loc) · 1 KB
/
Copy pathsensor.js
File metadata and controls
45 lines (37 loc) · 1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
var events = require('events'),
util = require('util');
/*
* Main Sensor constructor
* Process options
* Tell the board to set it up
*/
var Sensor = function (options) {
if (!options || !options.board) throw new Error('Must supply required options to Sensor');
this.board = options.board;
this.pin = options.pin || 'A0';
this.board.pinMode(this.pin, 'in');
// Poll for sensor readings
setInterval(function () {
this.board.analogRead(this.pin);
}.bind(this), options.throttle || 50);
// When data is received, parse inbound message
// match pin to instance pin value
this.board.on('data', function (message) {
var m = message.slice(0, -1).split('::'),
err = null,
pin, data;
if (!m.length) {
return;
}
pin = m[0]
data = m.length === 2 ? m[1] : null;
if (pin === this.pin) {
this.emit('read', err, data);
}
}.bind(this));
};
/*
* EventEmitter, I choose you!
*/
util.inherits(Sensor, events.EventEmitter);
module.exports = Sensor;