forked from espruino/EspruinoDocs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHMC5883.js
85 lines (69 loc) · 2.12 KB
/
HMC5883.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
/* Copyright (C) 2014 Spence Konde. See the file LICENSE for copying permission. */
/*
This module interfaces with an HMC5883 Compass/Magnetometer, a cheap I2C magnetometer.
Usage:
Setup I2C, then call:
var compass = require("HMC5883").connect(i2c,drdy,mode)
i2c is the I2C it is connected to, drdy is the pin that drdy is connected to.
read in single measurement mode:
compass.reads(function(a){print(a);});
read in continuous measurement mode:
compass.setmode(0);
console.log(compass.readc());
*/
exports.connect = function(i2c,drdy,mode) {
return new HMC5883(i2c,drdy,range);
}
function HMC5883(i2c,drdy,mode) {
this.i2c = i2c;
this.mode = (mode) ? mode : 1;
this.drdy = drdy;
this.a=0x1E;
pinMode(drdy,'input');
this.i2c.writeTo(this.a,1);
this.gain=(this.i2c.readFrom(this.a,1))>>5;
this.ngain=this.gain;
this.i2c.writeTo(this.a,[2,this.mode]);
this.scale=new Float32Array([0.73,0.92,1.22,1.52,2.27,2.56,3.03,4.35]);
}
HMC5883.prototype.readc = function() {
this.i2c.writeTo(this.a,3);
var f=this.scale[this.gain];
this.gain=this.ngain;
var gdat = this.i2c.readFrom(this.a,6)
var x = (gdat[0] << 8) | gdat[1];
var y = (gdat[2] << 8) | gdat[3];
var z = (gdat[4] << 8) | gdat[5];
x=(x>=32767) ? x - 65536 : x;
y=(y>=32767) ? y - 65536 : y;
z=(z>=32767) ? z - 65536 : z;
var o=(x==-4096 || y==-4096 || z==-4096);
return {x:x*f, y:y*f, z:z*f, overflow:o};
}
HMC5883.prototype.setMode = function(mode) {
this.i2c.writeTo(this.a,[2,(mode & 0x03)]);
this.mode=mode&0x03;
}
HMC5883.prototype.setup = function(sample,dout,ms) {
ms=(ms) ? ms&3 : 0;
dout=(dout) ? dout&7 : 4;
sample=sample&3;
this.i2c.writeTo(this.a,[0,ms|(dout<<2)|(sample<<5)]);
}
HMC5883.prototype.setGain = function(gain) {
this.i2c.writeTo(this.a,[1,((gain & 7)<<5)]);
this.i2c.writeTo(this.a,1);
this.ngain=(this.i2c.readFrom(this.a,1))>>5;
if (this.mode!=2) {
this.onwatch=c;
var hmc=this;
setWatch(function(){hmc.readc();},this.drdy);
this.setmode(1);
}
}
HMC5883.prototype.reads = function(c) {
this.onwatch=c;
var hmc=this;
setWatch(function(){hmc.onwatch(hmc.readc());},this.drdy);
this.setmode(1);
}