/
index.js
424 lines (380 loc) · 10.7 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
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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
// Copyright 2014 Technical Machine, Inc. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
var events = require('events');
var util = require('util');
// I2C Configuration
var I2C_ADDRESS = 0x73;
var LED0_ON_L = 0x06;
var LED0_ON_H = 0x07;
var LED0_OFF_L = 0x08;
var LED0_OFF_H = 0x09;
var MAX = 4096;
var MODE1 = 0x0;
var PRE_SCALE = 0xFE;
function servoController (hardware, low, high, addr2, addr3) {
/**
Constructor
Args
hardware
Tessel port to use
low
Minimum PWM value (should be 0-1.0 for best results)
high
Maximum PWM value (should be low-1.0 for best results)
addr2
I2C address bit 2
addr3
I2C address bit 3
*/
this.hardware = hardware;
// Set default high and low duty cycles for the module
this.low = low || 0.05;
if (low === 0) {
this.low = 0;
}
this.high = high || 0.12;
// Enable the outpts
hardware.digital[2].write(0);
// Configure I2C address
this.address = I2C_ADDRESS;
addr2 = addr2 || 0;
addr3 = addr3 || 0;
hardware.digital[1].write(addr2);
hardware.digital[0].write(addr3);
this.address |= addr2 << 2;
this.address |= addr3 << 3;
this.i2c = hardware.I2C(this.address);
// Store PWM settings for each servo individually
this.servoConfigurations = {};
}
util.inherits(servoController, events.EventEmitter);
// Reads fom the given registers on the PCA9685 via I2C and passes their replies to the callback
servoController.prototype._chainRead = function (registers, callback, replies) {
/**
Args
registers
An array of registers to read
callback
Callback; gets an array of reply bytes as an arg
replies
An array to which err, replies will be pushed
*/
var replies = replies || []; // jshint ignore:line
var self = this;
if (registers.length === 0) {
if (callback) {
callback(null, replies);
}
}
else {
self.i2c.transfer(new Buffer([registers[0]]), 1, function (err, data) {
if (err) {
if (callback) {
callback(err, replies);
}
}
replies.push(data[0]);
self._chainRead(registers.slice(1), callback, replies);
});
}
};
// Makes multiple writes to the PCA9685's registers via I2C
servoController.prototype._chainWrite = function (registers, data, callback) {
/**
Args
registers
An array of register addresses
data
An array of data payloads
callback
Callback
*/
var self = this;
if (registers.length === 0) {
if (callback) {
callback();
}
} else {
self.i2c.send(new Buffer([registers[0], data[0]]), function () {
self._chainWrite(registers.slice(1), data.slice(1), callback);
});
}
};
// Reads from registers on the PCA9685 via I2C
servoController.prototype._readRegister = function (register, callback) {
/**
Args
register
Register to read
callback
Callback; gets reply byte as its arg
*/
this.i2c.transfer(new Buffer([register]), 1, function (err, data) {
if (callback) {
callback(err, data[0]);
}
});
};
// Writes to registers on the PCA9685 via I2C
servoController.prototype._writeRegister = function (register, data, callback) {
/**
Args
register
Register to read
data
Bytes to send
callback
Callback
*/
this.i2c.send(new Buffer([register, data]), callback);
};
// Sets the PWM max and min for the specified servo
servoController.prototype.configure = function (index, low, high, callback) {
/**
Many hobby servos, motor speed controllers, etc. expect a nominal 20 ms
period and map duty cycles (% time the signal is high for a given period) of
10% and 20% to minimum and maximum positions, respectively. The protocol is
not particularly strict, though, so it is not uncommon for servos to respond
to duty cycles outside the 10%-20% range. This command allows each servo's
minimum and maximum PWM values to be controlled individually.
Args
index
Servo to configure
low
PWM lower bound (value for move(index, 0))
high
PWM upper bound (value for move(index, 1))
callback
Callback
*/
if (low >= high) {
var err = new Error('Minimum PWM must be smaller than maximum PWM.');
if (callback) {
callback(err);
}
return err;
}
this.servoConfigurations[index] = [low, high];
if (callback) {
callback(null);
}
};
// Get the PWM max and min for the specified servo
servoController.prototype.getConfiguration = function (index, callback) {
/**
Args
index
index of servo configuration to read. NOTE: 1-indexed
callback
Callback
Callback parameters
err
null
config
An array with the following contents:
0 - low
PWM lower bound (PWM value for move(index, 0))
1 - high
PWM upper bound (PWM value for move(index, 1))
Returns
config
as described above
*/
if (!this.servoConfigurations[index]) {
if (callback) {
callback(new Error('Specified servo channel has not been configured'), null);
}
return new Error('Specified servo channel has not been configured');
} else {
if (callback) {
callback(null, this.servoConfigurations[index]);
}
return this.servoConfigurations[index];
}
};
// Sets the position of the specified servo
servoController.prototype.move = function (index, val, callback) {
/**
Args
index
Index of the servo. NOTE: servos are 1-indexed
val
Position to which the the servo is to move. 0-1 of its full scale.
callback
Callback
*/
if (index < 1 || index > 16) {
var err = new Error('Servos are 1-indexed. Servos can be between 1-16.');
if (callback) {
callback(err);
}
return err;
}
if (val < 0 || val > 1) {
var err = new Error('Invalid position. Value must be between 0 and 1');
if (callback) {
callback(err);
}
return err;
}
// If unconfigured, use the controller's default values
if (!this.servoConfigurations[index]) {
this.configure(index, this.low, this.high, null);
}
var low = this.servoConfigurations[index][0];
var high = this.servoConfigurations[index][1];
this.setDutyCycle(index, (val * (high - low)) + low, callback);
};
// Reads the current approximate position target for the specified servo
servoController.prototype.read = function (servo, callback) {
/**
For each channel on the PCA9685, there are two 12 bit registers that
correspond to the counter values at which the line is set high and low. This
function reads these registers, calculates the theoretical duty cycle, and
then maps it against the range of duty cycles to which the servo is
calibrated in ```configure```. The ratio of the true duty cycle to the
range of configured duty cycles is passed to the callback.
Because this function cannot determine the true position of a physical servo
and the math it does is inherently lossy, we do not recommend using this
function in feedback loops.
Args
servo
The servo index
callback
Callback; gets err, approximate position target as args
*/
if (!this.servoConfigurations[servo]) {
if (callback) {
callback(new Error('Unconfigured servo cannot have a defined position. Configure your servo before reading.'), null);
}
}
var self = this;
var registers = [LED0_ON_L + (servo - 1) * 4,
LED0_ON_H + (servo - 1) * 4,
LED0_OFF_L + (servo - 1) * 4,
LED0_OFF_H + (servo - 1) * 4];
self._chainRead(registers, function (err, replies) {
// When in the count cycle the pin goes high
var on = replies[0] + (replies[1] << 8);
// When it goes low
var off = replies[2] + (replies[3] << 8);
// Duty cycle with no phase shift
var currentDuty = (off - on) / MAX;
var low = self.servoConfigurations[servo][0];
var high = self.servoConfigurations[servo][1];
var range = (high - low);
if (callback) {
callback(null, (currentDuty - low) / range);
}
return (currentDuty - low) / range;
});
};
// Sets the duty cycle for the specified servo
servoController.prototype.setDutyCycle = function (index, on, callback) {
/**
Args
index
Servo index to set
on
Duty cycle (0-1) for the specified servo
callback
Callback
*/
if (index < 1 || index > 16) {
var err = new Error('Servos are 1-indexed. Servos can be between 1-16.');
if (callback) {
callback(err);
}
return err;
}
if (on < 0 || on > 1) {
var err = new Error('Invalid duty cycle. Value must be between 0 and 1');
if (callback) {
callback(err);
}
return err;
}
var convertOn = 0;
var convertOff = Math.floor(MAX * on);
// Set up writes
var registers = [LED0_ON_L + (index - 1) * 4,
LED0_ON_H + (index - 1) * 4,
LED0_OFF_L + (index - 1) * 4,
LED0_OFF_H + (index - 1) * 4];
var data = [convertOn,
convertOn >> 8,
convertOff,
convertOff >> 8];
this._chainWrite(registers, data, callback);
};
// Sets the PWM frequency in Hz for the PCA9685 chip
servoController.prototype.setModuleFrequency = function (freq, callback) {
/**
Args
freq
PWM frequency, in units of Hertz
callback
Callback
*/
var prescaleVal = (25000000 / MAX) / freq - 1;
var prescale = Math.floor(prescaleVal);
var self = this;
self._readRegister(MODE1, function (err, oldMode) {
if (err) {
if (callback) {
callback(err, null);
}
return err;
}
var newMode = oldMode | 0x10;
var registers = [MODE1, PRE_SCALE, MODE1, MODE1];
var data = [newMode, prescale, oldMode, 0xa1];
self._chainWrite(registers, data, callback);
});
};
function use (hardware, low, high, callback) {
/**
Connect to the Servo Module
Args
hardware
Tessel port to use
low
Minimum duty cycle (0-1.0)
high
Maximum duty cycle (should be between low and 1.0 for best results)
callback
Callback
*/
if (typeof low == 'function') {
callback = low;
low = null;
}
var servos = new servoController(hardware, low, high);
servos.setModuleFrequency(50, function (err) {
if (!err) {
servos._connected = true;
setImmediate(function () {
servos.emit('ready');
});
if (callback) {
callback(null, servos);
}
} else {
setImmediate(function () {
servos.emit('error', err);
});
if (callback) {
callback(err);
}
}
});
return servos;
}
exports.use = use;
exports.servoController = servoController;