1. Introduction
Magnetometer extends the Generic Sensor API [GENERIC-SENSOR] to provide information about the magnetic field as detected by the device’s primary magnetometer sensor. The magnetometer sensor measures the magnetic field for all three physical axes (x, y, z) in μT (micro Tesla).
This specification defines two new interfaces:
-
Magnetometer
that reports calibrated magnetic field values, and -
UncalibratedMagnetometer
that reports uncalibrated magnetic field values.
The magnetic field is a field that exerts magnetic force on magnetometer sensor due to the magnetic effect generated by electric currents, magnetic materials or Earth’s magnetic force that is attributed to the combined effects of the planetary rotation and the movement of molten iron in the Earth’s core.
Hard iron distortion is created by objects that produce a magnetic field, such as magnetized iron.
Soft iron distortion stretches or distorts the magnetic field and is caused by metals such as nickel and iron.
The calibrated magnetic field is a magnetic field with hard iron distortion and soft iron distortion correction applied.
The uncalibrated magnetic field is the magnetic field without hard iron distortion correction and with soft iron distortion correction applied, and as such reports changes in the magnetic field caused by magnetized objects moving near the magnetometer.
2. Examples
let sensor = new Magnetometer(); sensor.start(); sensor.onchange = () => { console.log("Magnetic field along the X-axis " + sensor.x); console.log("Magnetic field along the Y-axis " + sensor.y); console.log("Magnetic field along the Z-axis " + sensor.z); }; sensor.onerror = event => console.log(event.error.name, event.error.message);
3. Security and Privacy Considerations
There are no specific security and privacy considerations beyond those described in the Generic Sensor API [GENERIC-SENSOR].
4. Model
The magnetometer has two associated Sensor
subclasses, Magnetometer
and UncalibratedMagnetometer
.
The Magnetometer
and UncalibratedMagnetometer
have an associated PermissionName
which is "magnetometer".
The latest reading per sensor of magnetometer includes three entries whose keys are "x", "y", "z" and whose values contain magnetic field about the corresponding axes. Values can contain also device’s uncalibrated magnetic field and hard iron distortion depending on which object was instantiated.
For uncalibrated magnetometer, the latest reading includes three entries whose keys are "x", "y", "z" and whose values contain uncalibrated magnetic field around the 3 different axes, and three additional entries whose keys are "xBias", "yBias", "zBias" and whose values contain the hard iron distortion correction around the 3 different axes.
The sign of the magnetic field values must be according to the right-hand convention in a local coordinate system defined by the device.
Note: The local coordinate system of a mobile device is usually defined relative to the device’s screen when the device in its default orientation (see figure below).
5. API
5.1. The Magnetometer Interface
[Constructor(optional SensorOptions sensorOptions)] interface Magnetometer : Sensor { readonly attribute unrestricted double? x; readonly attribute unrestricted double? y; readonly attribute unrestricted double? z; };
5.2. The UncalibratedMagnetometer Interface
[Constructor(optional SensorOptions sensorOptions)] interface UncalibratedMagnetometer : Sensor { readonly attribute unrestricted double? x; readonly attribute unrestricted double? y; readonly attribute unrestricted double? z; readonly attribute unrestricted double? xBias; readonly attribute unrestricted double? yBias; readonly attribute unrestricted double? zBias; };
To Construct a Magnetometer Object, or to Construct an UncalibratedMagnetometer Object the user agent must invoke the construct a Sensor object abstract operation.
5.2.1. Magnetometer.x
The x
attribute of the Magnetometer
interface represents the magnetic field around X-axis.
In other words, this attribute returns latest reading["x"].
5.2.2. Magnetometer.y
The y
attribute of the Magnetometer
interface represents the magnetic field around Y-axis.
In other words, this attribute returns latest reading["y"].
5.2.3. Magnetometer.z
The z
attribute of the Magnetometer
interface represents the magnetic field around Z-axis.
In other words, this attribute returns latest reading["z"].
5.2.4. UncalibratedMagnetometer.x
The x
attribute of the UncalibratedMagnetometer
interface represents the uncalibrated magnetic field around X-axis.
In other words, this attribute returns latest reading["x"].
5.2.5. UncalibratedMagnetometer.y
The y
attribute of the UncalibratedMagnetometer
interface represents the uncalibrated magnetic field around Y-axis.
In other words, this attribute returns latest reading["y"].
5.2.6. UncalibratedMagnetometer.z
The z
attribute of the UncalibratedMagnetometer
interface represents the uncalibrated magnetic field around Z-axis.
In other words, this attribute returns latest reading["z"].
5.2.7. UncalibratedMagnetometer.xBias
The xBias
attribute of the UncalibratedMagnetometer
interface represents the hard iron distortion correction around X-axis.
In other words, this attribute returns latest reading["xBias"].
5.2.8. UncalibratedMagnetometer.yBias
The yBias
attribute of the UncalibratedMagnetometer
interface represents the hard iron distortion correction around Y-axis.
In other words, this attribute returns latest reading["yBias"].
5.2.9. UncalibratedMagnetometer.zBias
The zBias
attribute of the UncalibratedMagnetometer
interface represents the hard iron distortion correction around Z-axis.
In other words, this attribute returns latest reading["zBias"].
6. Limitations of Magnetometer Sensors
This section is non-normative.
The direction and magnitude of the Earth’s field changes with location, latitude in particular. For example, the magnitude is lowest near the equator and highest near the poles. Some hard-iron interference, meaning presence of permanent magnets (e.g. magnets in the speaker of a phone) in the vicinity of the sensor also affects the accuracy of the reading. Presence of electronic items, laptops, batteries, etc also contribute to the soft iron interference. Flight Mode option in mobile phones might help in decreasing the electro magnetic interference.
In addition to the above spatial variations of the magnetic field, time based variations, like solar winds or magnetic storms, also distort the magnetosphere or external magnetic field of the earth.
7. Use Cases and Requirements
Magnetometers can be used for a variety of use-cases, such as:
-
Metal detector web application.
-
Providing input using magnetic button for VR enclosures [VRBUTTON].
-
Gesture recognition based on magnetic field. Various interactions like writing, signing and playing an instrument can also be enabled using a magnet like a rod, pen or a ring [MAGITACT]. The user makes coarse gestures in the 3D space around the device using the magnet. Movement of the magnet affects the magnetic field sensed by the compass sensor integrated in the device. The temporal pattern of the gesture is then used as a basis for sending different interaction commands to the mobile device. Zooming, turning pages, accepting/rejecting calls, clicking items are some of the use cases.
-
In cases, where it is not possible to use orientation-sensor, user may need to fuse magnetometer data with with other low-level sensor data, to calculate orientation.
-
Indoor navigation system may use magnetometer on mobile phones [MAGINDOORPOS]. Specific use cases for indoor navigation may include proximity advertising, way finding in malls or airports, geofencing, etc.
-
Calculating compass heading, more on that in §8 Compass Heading Using Magnetometers.
Metal detection and input using magnetic button may require only coarse data and low sampling rates suffice. Gesture recognition or indoor navigation are more real time use cases where there might be a need for more accurate sensor readings and higher sampling rates. Head mount tracking in Virtual Reality may require sensor fusion from accelerometer, gyroscope and magnetometer. Magnetometer data may be used to help in calibration of gyroscope readings and align yaw readings with the magnetic north. The required sampling rate might depend on the sensor fusion algorithm and characteristics of other motion sensors involved.
8. Compass Heading Using Magnetometers
Compasses, instruments that align themselves with the magnetic poles of the Earth, have been used in navigation for centuries. The earth’s rotational axis defines the geographic north and south poles that we use for map references. It turns out that there is a discrepancy of around 11.5 degrees (around 1000 miles) between the geographic poles and the magnetic poles. Declination angle is applied to the magnetic direction to correct for this situation.
If the device is always level to the earth’s surface, compass heading [COMPASSHEADING] can be determined by using just the x
and y
component of the earth’s magnetic field, that
is, the directions planar with the earth’s surface.
To determine geographic north (or true north) heading, add the appropriate declination angle.
Magnetic declination or declination angle is the angle on the horizontal plane between magnetic north and the true north and depends on the position on the Earth’s surface, and changes over time. By convention, declination is positive when magnetic north is east of true north, and negative when it is to the west. You can get real time value for magnetic declination e.g. using the Magnetic declination calculator provided by the National Oceanic and Atmospheric Administration (NOAA).
Magnetic north calculation is simple:
let sensor = new Magnetometer(); sensor.start(); var headingDegrees = Math.atan2(sensor.y, sensor.x) * (180 / Math.PI); console.log('Heading in degrees: ' + headingDegrees);
To get geographic north (or true north) that considers the magnetic declination at the given latitude and longitude, further work is required:
// First, get the latitude and longitude (omitted for brevity). var latitude = 0, longitude = 0; // Then, get the magnetic declination using your favorite web service. var base = 'https://www.ngdc.noaa.gov/geomag-web/calculators/calculateDeclination'; fetch(base + '?lat1=' + latitude + '&lon1=' + longitude + '&resultFormat=csv') .then(response => response.text()).then(text => { var declinationDegrees = parseFloat(text.replace(/^#.*$/gm, '').trim().split(',')[4]); // Compensate for the magnetic declination to get the true north. console.log('True heading in degrees: ' + (headingDegrees + declinationDegrees)); });
Note: If the device is not level to the Earth’s surface, a developer needs to apply various tilt compensation techniques for which she needs a 3-axis accelerometer. Data from the orientation sensor, which is a fusion of the accelerometer and magnetometer sensors, is required to implement this particular use case.
9. Acknowledgements
Tobie Langel for the work on Generic Sensor API.
10. Conformance
Conformance requirements are expressed with a combination of descriptive assertions and RFC 2119 terminology. The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in the normative parts of this document are to be interpreted as described in RFC 2119. However, for readability, these words do not appear in all uppercase letters in this specification.
All of the text of this specification is normative except sections explicitly marked as non-normative, examples, and notes. [RFC2119]
A conformant user agent must implement all the requirements listed in this specification that are applicable to user agents.
The IDL fragments in this specification must be interpreted as required for conforming IDL fragments, as described in the Web IDL specification. [WEBIDL]