/
board.js
125 lines (101 loc) · 2.48 KB
/
board.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
var util = require('util')
var events = require('events')
/**
* A board class wraps the firmata object
* The board class provides shortcuts for writing/reading data
*/
function Board(port, firmata) {
this.port = port
this.firmata = firmata
var self = this
this.Component = function(config) {
return new Component(self, config)
}
}
Board.prototype.pins = function() {
var pins = Array.prototype.slice.call(arguments)
return new this.Component({
pins: pins
})
}
exports.Board = Board
function Component(board, config) {
this.board = board
// Standardize config
// Use array of pins
if (config.pins && !Array.isArray(config.pins)) {
config.pins = [config.pins]
} else if(config.pin && !config.pins) {
config.pins = [config.pin]
delete config.pin
}
this.config = config
}
util.inherits(Component, events.EventEmitter)
Component.prototype.mode = function(mode, pins) {
pins = pins || this.config.pins
pins.forEach(function(pin) {
this.board.firmata.pinMode(pin, this.board.firmata.MODES[mode])
}.bind(this))
return this
}
Component.prototype.output = function(pins) {
this.mode('OUTPUT', pins)
return this
}
Component.prototype.low = function(pins) {
pins = pins || this.config.pins
pins.forEach(function(pin) {
this.board.firmata.digitalWrite(pin, this.board.firmata.LOW)
}.bind(this))
return this
}
Component.prototype.high = function(pins) {
pins = pins || this.config.pins
pins.forEach(function(pin) {
this.board.firmata.digitalWrite(pin, this.board.firmata.HIGH)
}.bind(this))
return this
}
Component.prototype.pulse = function(value, pulseOut) {
this.board.firmata.setMaxListeners(100)
value = value || this.board.firmata.HIGH
pulseOut = pulseOut || 5
var settings = {
pulseOut: pulseOut,
value: value,
pin: this.config.pins[0]
}
this.board.firmata.pulseIn(settings, function(duration) {
this.emit('read', duration)
}.bind(this))
return this
}
Component.prototype.write = function(value) {
this.board.firmata.analogWrite(this.config.pins[0], value)
return this
}
Component.prototype.read = function(callback) {
var pin = this.config.pins[0]
var method = 'digitalRead'
var mode = 'INPUT'
// Analog case
if (pin.length && pin.length > 1) {
mode = 'ANALOG'
method = 'analogRead'
pin = pin.substring(1)
} else {
this.mode(mode)
}
this.board.firmata[method](pin, function( data ) {
callback(data)
})
return this
}
/**
* Writes a PWM value to the pin
*/
Component.prototype.pwm = function(value) {
this.mode('PWM')
this.write(value)
}