Using Magnetometer(HMC5883L) with arduino !

Magnetometer(s) are great nifty components which you can incorporate into your projects . They can sense the magnitude of tilt in any of the direction. Magnetometer(s) are use in your smartphones and tablets to detect orientation and play games .


In this tutorial i will be using HMC 5883L module to demonstrate the usage of Magnetometer(s)with arduino .

Materials Required :

(1) HMC 583L Magnetometer module .


(2) Arduino board .

(3) Breadboard

(4) 4xLed (Of any color)

(5) Jumper Wires

(6) A working brain (Most essential ! )

Procedure :

Wiring :

(1) Insert the HMC 5883L module to breadboard .

(3) Connect VCC To arduino 3.3 Volts  and GND To arduino ground  {Remember : This module can’t work on 5 volts , so be careful !)

(4) Connect SDA To Pin A4 And SCL to Pin A5 {In case of mega : Connect SCL to SCL and SDA to SDA }

(5) Connect anodes your  Led(s) to digital pins 11 , 12 and 13 .

(6) Connect cathodes of your LED(s) to ground .

Code :

(5) Now , download and install Adafruit’s Sensor library from here .

(6)Download and install HMC 5883L library form here .

(7) I have made code for you guys ! you can download it from here .

(8) Connect your arduino board and upload the code .

Explanation :

What this code does is that it constantly monitors the output from the sensor and when ever it detects a certain amount of tilt on any of the or axis it turns on the respective LED .

You can tinker the amount of tilt by editing this code :

if(y>10) {
else {
digitalWrite(12 ,LOW);
if(x>30) {
if (y<-20) {
analogWrite(A0 ,250);
else {
analogWrite(A0 ,0);

I hope this post was useful for you !

Stay tuned for more future posts !