forked from byoung2/node-berryimu
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
73 lines (69 loc) · 2.91 KB
/
index.js
File metadata and controls
73 lines (69 loc) · 2.91 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
var sensors = require('./sensors');
var BerryIMU = function(device) {
this.accelerometer = new sensors.Accelerometer(null, device);
this.magnetometer = new sensors.Magnetometer(null, device);
this.gyroscope = new sensors.Gyroscope(null, device);
this.barometer = new sensors.Barometer(null, device);
this.state = {};
};
module.exports = BerryIMU;
BerryIMU.prototype.initialize = function(callback) {
var _this = this;
_this.accelerometer.initialize(function() {
_this.magnetometer.initialize(function() {
_this.gyroscope.initialize(callback);
});
});
};
BerryIMU.prototype.update = function(callback) {
var _this = this;
_this.accelerometer.update(function() {
_this.gyroscope.update(function() {
_this.magnetometer.update(function() {
_this.barometer.update(function() {
var accX = _this.accelerometer.x;
var accY = _this.accelerometer.y;
var accZ = _this.accelerometer.z;
var magX = _this.magnetometer.x;
var magY = _this.magnetometer.y;
// calculate pitch, yaw & roll
var toRad = Math.PI / 180;
var now = new Date();
if (!_this.state.lastUpdate) _this.state.lastUpdate = now;
var accXNorm = accX/Math.sqrt(accX * accX + accY * accY + accZ * accZ);
var accYNorm = accY/Math.sqrt(accX * accX + accY * accY + accZ * accZ);
var pitch = Math.atan2(accY, accZ) * (180 / Math.PI);
var yaw = Math.atan2(magY, magX) / (180 / Math.PI);
var roll = Math.atan2(accX, accZ) * (180 / Math.PI);
_this.state.lastPitch = (_this.state.lastPitch) ? _this.pitch : pitch;
_this.state.lastYaw = (_this.state.lastYaw) ? _this.yaw : yaw;
_this.state.lastRoll = (_this.state.lastRoll) ? _this.roll : roll;
_this.pitch = pitch < 0 ? pitch + 360 : pitch;
_this.yaw = yaw < 0 ? yaw + 360 : yaw;
_this.roll = roll < 0 ? roll + 360 : roll;
_this.gravity = {
x: -1 * Math.sin(_this.yaw / (180 / Math.PI)),
y: Math.cos(_this.yaw / (180 / Math.PI)) * Math.sin(_this.roll / (180 / Math.PI)),
z: Math.cos(_this.yaw / (180 / Math.PI)) * Math.cos(_this.roll / (180 / Math.PI))
},
_this.gravity.force = Math.sqrt(Math.pow(_this.gravity.x, 2) + Math.pow(_this.gravity.y, 2) + Math.pow(_this.gravity.z, 2));
// calculate velocity
_this.velocity = {
linear: {
x: 0,
y: 0,
z: 0
},
angular: {
x: (_this.pitch - _this.state.lastPitch) / (now - _this.state.lastUpdate) * toRad,
y: (_this.roll - _this.state.lastRoll) / (now - _this.state.lastUpdate) * toRad,
z: (_this.yaw - _this.state.lastYaw) / (now - _this.state.lastUpdate) * toRad
}
};
_this.state.lastUpdate = now;
callback();
});
});
});
});
};