This repository was archived by the owner on Jan 21, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.js
More file actions
54 lines (43 loc) · 1.3 KB
/
index.js
File metadata and controls
54 lines (43 loc) · 1.3 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
46
47
48
49
50
51
52
53
54
var gpio = require('rpi-gpio');
var util = require('util');
var events = require('events');
function changed(previous, next, lastChanged, delay) {
return (previous !== next) &&
(Date.now() - lastChanged >= delay);
}
/**
* Listen for a pin
* @param {Object} config
* - pin: pin to listen to
* - interval: poll interval (ms)
* - delay: how much time should pass before registering
* another change (s)
*/
function Pinhead(config) {
this.pin = config.pin;
this.interval = config.interval || 10;
this.delay = (config.delay * 1000) || 5000;
events.EventEmitter.call(this);
gpio.setup(this.pin, gpio.DIR_IN, this.read.bind(this));
}
util.inherits(Pinhead, events.EventEmitter);
Pinhead.prototype.read = function() {
var _this = this;
var previous = -1;
var changeTime = Date.now();
this.emit('ready');
setInterval(function () {
gpio.read(_this.pin, function (err, val) {
_this.emit('data', val);
if (err) _this.emit('error', err);
if (changed(previous, val, changeTime, _this.delay)) {
changeTime = Date.now();
_this.emit('change', val);
}
previous = val;
});
}, this.interval);
};
module.exports = function(config) {
return new Pinhead(config);
};