praneshkmr / node-lsm303

Node.js Library for LSM303
MIT License
7 stars 7 forks source link

Feature Request for Heading #2

Closed ActionNerd closed 9 years ago

ActionNerd commented 9 years ago

I'm interested in contributing a feature for heading. This would allow a person to get straight magnetic heading 0 - 360 rather than have to fuss with translating cartesian to polar. It would require an addition of a toPolar function in util.js:

var toPolar = function(x, y) { // returns polar coordinates as an object (radians)
  var polarCoords = {};
  polarCoords.r = Math.sqrt(x * x + y * y);
  // atan2 provides CCW angle from the positive x axis; this piece normalizes it
  // to 0 - 2Pi (0 - 360 in radians) from the positive Y axis
  polarCoords.theta = Math.PI / 2 - Math.atan2(y, x);
  if ( polarCoords.theta < 0 ) {
    polarCoords.theta += 2 * Math.PI;
  }
  return (360 - (180 / Math.PI * polarCoords.theta)); // Returning theta alone (heading)
}

And then, the addition of a buffToHead function:

Utils.buffToHeadMag = function(buffer){
  var pos;
  pos = {
    x: (this.twoscomp((buffer[0] << 8) | buffer[1],16) - this.x_offset),
    z: (this.twoscomp((buffer[2] << 8) | buffer[3],16) - this.z_offset),
    y: (this.twoscomp((buffer[4] << 8) | buffer[5],16) - this.y_offset)
  }
  return toPolar(pos.x, pos.y);
}

Then, the addition of a readHeading function in Magnetometer:

Magnetometer.prototype.readHeading = function(callback){
    this.mag.readBytes(0x03, 6, function(err, res) {
        callback(err, utils.buffToHeadMag(res));
    });
}

I know there is still a little work to be done there, but I think I can have it ready in a few days. Thoughts?