keepcalculator

06 Numbers and Powers

3-Axis Magnetic Sensor Tracking: How It Works

Card No. 06·49807 · Updated · Standard formula, shown below

This guide explains how a tiny magnetic sensor can track motion in three axes, a technique used in everything from smartphone compasses to VR controllers. You will learn the core principle—measuring changes in the Earth’s magnetic field—and how to turn raw sensor data into usable motion tracking. No prior electronics experience is needed, but a basic understanding of coordinates helps.

What You’ll Need

  • A 3-axis magnetometer (e.g., a small breakout board with an I2C interface)
  • A microcontroller (Arduino, Raspberry Pi, or similar) with I2C support
  • Jumper wires and a breadboard (or soldering equipment if you prefer)
  • A computer with the necessary IDE (Arduino IDE, Python, etc.)
  • A non-magnetic surface to work on (avoid steel tables)

Step-by-Step

  1. Understand the physics. A magnetometer measures the strength and direction of the magnetic field along three perpendicular axes (X, Y, Z). When the sensor moves, the Earth’s magnetic field vector relative to the sensor changes. By tracking these changes over time, you can infer rotation and, with some processing, linear motion.
  2. Connect the sensor. Wire the magnetometer to your microcontroller using I2C: connect VCC to 3.3V or 5V (check your sensor’s spec), GND to ground, SDA to the I2C data pin, and SCL to the I2C clock pin. On an Arduino Uno, SDA is A4 and SCL is A5.
  3. Install the necessary library. In your IDE, search for the sensor’s library (e.g., Adafruit Magnetometer, HMC5883L, or LIS3MDL). Install it. This library will handle the low-level communication.
  4. Initialize the sensor. Write a setup function that starts the I2C communication and initializes the magnetometer. Set the measurement range (e.g., ±1.3 to ±8.1 gauss) and the data rate (e.g., 100 Hz).
  5. Read raw data. In the main loop, read the X, Y, and Z values from the sensor. These are raw integers that represent the magnetic field strength in each axis. Print them to the serial monitor to verify they change when you move the sensor.
  6. Calibrate for hard-iron distortion. Rotate the sensor in a figure-8 pattern for about 30 seconds. Record the minimum and maximum values for each axis. Compute the offset for each axis: (max + min) / 2. Subtract this offset from every reading. This corrects for nearby magnets or metal that distort the field.
  7. Calibrate for soft-iron distortion. After hard-iron calibration, the range of each axis may still differ. Scale each axis so that the range (max – min) is the same for all three. This corrects for non-uniform magnetic materials near the sensor.
  8. Convert to a direction vector. After calibration, the three values represent the Earth’s magnetic field vector in the sensor’s local coordinate system. Normalize this vector to unit length to get a direction.
  9. Track rotation. To track orientation, you need to compare the current vector to a reference (e.g., the vector when the sensor was first powered on). The angle between the current and reference vectors gives the rotation about the axis perpendicular to both. For full 3D orientation, you need a gyroscope and an accelerometer (a 9-axis IMU). The magnetometer alone can only give you heading (yaw) relative to magnetic north, not pitch or roll, unless you combine it with other sensors.
  10. Track linear motion (optional). Magnetic sensors are not ideal for linear motion tracking because the Earth’s field is nearly uniform over small distances. To track linear movement, you would need to detect changes in the field gradient, which requires a very strong, non-uniform magnetic source (like a magnet placed nearby). In practice, for motion tracking in three axes, you use a combination of accelerometer, gyroscope, and magnetometer (an IMU). The magnetometer helps correct drift in the yaw axis.
  11. Apply sensor fusion. To get smooth, accurate 3D motion tracking, implement a sensor fusion algorithm (like a complementary filter or a Kalman filter). This combines the accelerometer (for pitch and roll), the gyroscope (for fast rotation), and the magnetometer (for yaw reference) to produce a reliable orientation in 3D space. Libraries like Madgwick or Mahony can do this for you.
  12. Test and refine. Mount the sensor on an object, run the fusion algorithm, and observe the output (e.g., Euler angles or quaternion). Move the object in all three axes and verify the tracking is responsive and stable. Adjust filter parameters (like the gain) to balance responsiveness vs. noise.

Common Mistakes

  • Forgetting to calibrate: raw magnetometer data is almost always distorted by nearby metal, leading to incorrect readings.
  • Using a steel table or having magnets nearby (like in a phone speaker) will skew readings.
  • Assuming the magnetometer alone can track all three axes of motion. It only measures magnetic field direction, not acceleration or rotation rate.
  • Mixing up I2C pins or using wrong voltage levels, which can damage the sensor.
  • Neglecting to normalize the vector, leading to inconsistent scale between axes.
  • Not considering the Earth’s field strength (about 25-65 microtesla) when setting the sensor range; too high a range reduces resolution.

Tips

  • Always calibrate in the environment where you will use the sensor, as nearby metal objects change the distortion.
  • Use a non-magnetic screwdriver and standoffs when mounting the sensor to avoid introducing hard-iron errors.
  • For better accuracy, use a 9-axis IMU (accelerometer + gyroscope + magnetometer) and a fusion library.
  • Sample at a rate at least twice the highest frequency of motion you want to track (Nyquist theorem).
  • Apply a low-pass filter to the magnetometer data to reduce noise, but be careful not to introduce lag.
  • If you need linear position (not just orientation), consider using a camera or beacons instead of a magnetometer.

Troubleshooting

  • No data or all zeros: Check wiring, I2C address (often 0x1E or 0x0D), and power. Use an I2C scanner to find the address.
  • Readings jump wildly: Likely uncalibrated or near a changing magnetic field (e.g., a motor). Move away from interference and recalibrate.
  • Heading drifts over time: The magnetometer is affected by temperature and nearby moving metal. Recalibrate periodically or use a gyroscope to correct drift.
  • Pitch and roll are wrong: The magnetometer cannot determine pitch and roll without an accelerometer. Use a fusion algorithm with an accelerometer.
  • Values saturate at max/min: The sensor range is too low. Increase the range in the sensor’s configuration register.
  • I2C communication fails: Check for pull-up resistors (most breakboards have them). Try lowering the I2C speed to 100 kHz.

Frequently Asked Questions

Can a single magnetometer track 3D position?

No. A magnetometer measures the magnetic field vector at a point. To get position, you need to sense a field gradient, which is not feasible with a single sensor in the Earth’s uniform field. You need an IMU with accelerometer and gyroscope for full motion tracking.

How does a magnetometer help in a smartphone’s motion tracking?

It provides a stable reference for yaw (heading) to correct the drift of the gyroscope. The accelerometer and gyroscope handle pitch and roll, and the magnetometer keeps the compass direction accurate.

What is the difference between a magnetometer and a compass?

A compass is a simple device that points north. A magnetometer measures the full 3D magnetic field, which can be used to compute heading, but also to detect the presence of magnets or to measure field strength.

Why do I need to calibrate the magnetometer?

Because the sensor is affected by nearby ferromagnetic materials (hard-iron) and by distortions in the field itself (soft-iron). Calibration removes these biases so the readings accurately reflect the Earth’s field.

Can I use a magnetometer to track a drone’s orientation?

Yes, but only for yaw. Drones typically use a 9-axis IMU (accelerometer, gyroscope, magnetometer) to get full orientation. The magnetometer is essential for maintaining heading, especially when the accelerometer cannot detect yaw.

What is the best sampling rate for motion tracking?

It depends on the motion speed. For human hand movements, 100 Hz is usually sufficient. For fast rotations, 400 Hz or higher may be needed. Always filter the data to remove aliasing.

Related

Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.

More cards in this drawer

The whole Numbers and Powers drawer →