HMC5883L 3-Axis Magnetometer

The HMC5883L [1] is a Triple-Axis Magnetometer or digital compass with an I2C output. The default resolution is about 0.92 milli-Gauss per unit, with a recommended range of ±1.3 Gauss.

It will operate from between 2.16V and 3.6V, so you need a regulator and logic-level conversion to operate it from a 5V board.

Although Adafruit and Sparkfun have discontinued their HMC5883L breakout boards, there are several Chinese boards available on eBay:


The I2C address is #x1E or 30.

Reading the magnetometer

The following routine s16 returns a signed 16-bit integer from two bytes, MSB first:

(defun s16 (s)
  (let ((d (logior (ash (read-byte s) 8) (read-byte s))))
    (- d (ash (logand d #x8000) 1))))

Here's the routine xyz to read the HMC5883L:

(defun xyz ()
  (with-i2c (s 30) 
    (write-byte 2 s) ; Mode register
    (write-byte 1 s) ; Single measurement
    (restart-i2c s 6)
    (let ((x (s16 s))
          (z (s16 s))
          (y (s16 s)))
      (list x y z))))

It returns a list of three integers for the three axes, in the order (x y z). For example:

> (xyz)
(-120 -186 -337)

  1. ^ HMC5883L Datasheet on Adafruit.