UNPKG

2.38 kBJavaScriptView Raw
1var Emitter = require("events").EventEmitter;
2var util = require("util");
3
4var Board = require("./board");
5var Fn = require("./fn");
6var within = require("./mixins/within");
7
8var toFixed = Fn.toFixed;
9
10var priv = new Map();
11
12/**
13 * Ping
14 * @param {Object} opts Options: pin
15 */
16
17function Ping(opts) {
18
19 if (!(this instanceof Ping)) {
20 return new Ping(opts);
21 }
22
23 var last = null;
24
25 Board.Component.call(
26 this, opts = Board.Options(opts)
27 );
28
29 this.pin = opts && opts.pin || 7;
30 this.freq = opts.freq || 20;
31 // this.pulse = opts.pulse || 250;
32
33 var state = {
34 value: null
35 };
36
37 // Private settings object
38 var settings = {
39 pin: this.pin,
40 value: this.io.HIGH,
41 pulseOut: 5
42 };
43
44 this.io.setMaxListeners(100);
45
46 // Interval for polling pulse duration as reported in microseconds
47 setInterval(function() {
48 this.io.pingRead(settings, function(microseconds) {
49 state.value = microseconds;
50 });
51 }.bind(this), 225);
52
53 // Interval for throttled event
54 setInterval(function() {
55 if (state.value === null) {
56 return;
57 }
58
59 // The "read" event has been deprecated in
60 // favor of a "data" event.
61 this.emit("data", state.value);
62
63 // If the state.value for this interval is not the same as the
64 // state.value in the last interval, fire a "change" event.
65 if (state.value !== last) {
66 this.emit("change", state.value);
67 }
68
69 // Store state.value for comparison in next interval
70 last = state.value;
71
72 // Reset samples;
73 // samples.length = 0;
74 }.bind(this), this.freq);
75
76 Object.defineProperties(this, {
77 value: {
78 get: function() {
79 return state.value;
80 }
81 },
82 // Based on the round trip travel time in microseconds,
83 // Calculate the distance in inches and centimeters
84 inches: {
85 get: function() {
86 return toFixed(state.value / 74 / 2, 2);
87 }
88 },
89 in: {
90 get: function() {
91 return this.inches;
92 }
93 },
94 cm: {
95 get: function() {
96 return toFixed(state.value / 29 / 2, 3);
97 }
98 }
99 });
100
101 priv.set(this, state);
102}
103
104util.inherits(Ping, Emitter);
105
106Object.assign(Ping.prototype, within);
107
108module.exports = Ping;
109
110
111//http://itp.nyu.edu/physcomp/Labs/Servo
112//http://arduinobasics.blogspot.com/2011/05/arduino-uno-flex-sensor-and-leds.html
113//http://protolab.pbworks.com/w/page/19403657/TutorialPings