-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
60 lines (47 loc) · 1.2 KB
/
index.js
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
55
56
57
58
59
60
var tessel = require('tessel');
var events = require('events');
var util = require('util');
var port = tessel.port['GPIO'];
var trig = port.digital[1];
var echo = port.digital[2];
function Proximity(trigger, echo, callback) {
this.trigger = trigger;
this.echo = echo;
setImmediate(function ready() {
this.emit('ready');
}.bind(this));
if (callback) {
callback(null, this);
}
return this;
}
util.inherits(Proximity, events.EventEmitter);
Proximity.prototype.triggerRead = function() {
this.trigger.write(1);
setTimeout(function off() {
this.trigger.write(0);
}.bind(this), 10);
}
Proximity.prototype.getDistance = function(callback) {
this.triggerRead(trig);
this.echo.readPulse('high', 1000, function(err, duration) {
if (err) {
if (callback) {
callback(err);
}
return;
}
var distance = ((duration * 1000)/2) / 29.1;
setImmediate(function() {
this.emit('data', distance);
}.bind(this));
if (callback) {
callback(null, distance);
}
}.bind(this));
}
function use(trigger, echo, callback) {
return new Proximity(trigger, echo, callback);
}
module.exports.use = use;
module.exports.Proximity = Proximity;