Engineers Garage

  • Electronic Projects & Tutorials
    • Electronic Projects
      • Arduino Projects
      • AVR
      • Raspberry pi
      • ESP8266
      • BeagleBone
      • 8051 Microcontroller
      • ARM
      • PIC Microcontroller
      • STM32
    • Tutorials
      • Audio Electronics
      • Battery Management
      • Brainwave
      • Electric Vehicles
      • EMI/EMC/RFI
      • Hardware Filters
      • IoT tutorials
      • Power Tutorials
      • Python
      • Sensors
      • USB
      • VHDL
    • Circuit Design
    • Project Videos
    • Components
  • Articles
    • Tech Articles
    • Insight
    • Invention Stories
    • How to
    • What Is
  • News
    • Electronic Product News
    • Business News
    • Company/Start-up News
    • DIY Reviews
    • Guest Post
  • Forums
    • EDABoard.com
    • Electro-Tech-Online
    • EG Forum Archive
  • DigiKey Store
    • Cables, Wires
    • Connectors, Interconnect
    • Discrete
    • Electromechanical
    • Embedded Computers
    • Enclosures, Hardware, Office
    • Integrated Circuits (ICs)
    • Isolators
    • LED/Optoelectronics
    • Passive
    • Power, Circuit Protection
    • Programmers
    • RF, Wireless
    • Semiconductors
    • Sensors, Transducers
    • Test Products
    • Tools
  • Learn
    • eBooks/Tech Tips
    • Design Guides
    • Learning Center
    • Tech Toolboxes
    • Webinars & Digital Events
  • Resources
    • Digital Issues
    • EE Training Days
    • LEAP Awards
    • Podcasts
    • Webinars / Digital Events
    • White Papers
    • Engineering Diversity & Inclusion
    • DesignFast
  • Guest Post Guidelines
  • Advertise
  • Subscribe

How to design a digital compass using Arduino and an HMC5883L magnetometer

By Nikhil Agnihotri March 22, 2022

Digital compasses are electronic devices that use sensors to determine the magnetic field, displaying the navigational direction numerically.

These types of compasses typically use a magnetometer sensor to measure the strength of the magnetic field to detect the direction. One low-cost, three-axis digital magnetometer is the HMC5883L. It measures the value of the magnetic field along the X, Y, and Z-axis, ranging from milligauss to eight gausses.

The HMC5883L shares the magnetic field values, in 16-bit resolution, using the I2C serial communication protocol. These values can then be used to compute the heading direction and heading degrees.

The HMC5833L can be easily interfaced with Arduino via the I2C port.

For this project, we’ll design a digital compass using the HMC5833L and SSD1306 OLED (organic light-emitting diode). The OLED display shows the heading degrees and a graphical compass rose, which changes in real time.

Components required

1. Arduino Uno x1
2. HMC5833L x1
3. SSD1306 OLED x1
4. Breadboard
5. Connecting wires/Jumper wires

Circuit connections
To make this digital compass, we’ll first need to interface the HCM5833L magnetometer and SSD1306 OLED display with Arduino Uno.

The HCM5833L breakout board has this pin configuration…

For the circuit connections, connect the HMC5883L’s VCC and GND pins with Arduino Uno’s 3.3V out and GND pin. It’s important to note that the HMC5883L cannot tolerate Arduino’s 5V supply and may get damaged if mistakenly connected to the 5V out. So, only use the 3.3V out.

The HCM5883L’s SCL and SDA pins should be connected to Arduino’s SCL and SDA pins, respectively. Leave the breakout board’s DRDY pin unconnected.

The OLED display provides the compass’ digital graphics, including the heading degrees. The SSD1306 is interfaced with Arduino using its physical SPI port.

To do so, connect the SSD1306 OLED’s D0/SCK and D1/MOSI pins with Arduino’s pins D13 and D11, respectively. Next, connect the SSD1306’s DC, RESET, and CS pins with Arduino’s D9, D10, and D8 pins, respectively.

 

Arduino sketch

How the circuit works
The HMC5883L outputs the magnetic field strength along three axes over the I2C protocol. The chip contains 12, built-in registers.

  • The value of the magnetic field along the X-axis is stored in registers 0x03 and 0x04.
  • The value of the magnetic field along the Z-axis is stored in registers 0x05 and 0x06.
  • The value of the magnetic field along the Y-axis is stored in registers 0x07 and 0x08.
  • The magnetometer can be configured by programming its registers to 0x00 and 0x01.
  • The mode of the compass can be set by programming the register 0x02.

Arduino configures the registers 0x00 and 0x01 to set the gain settings to +/- 1.3 Ga. The sampling rate is kept at a default of 1.

Similarly, the data output rate is configured to default 15, selecting the default normal measurement configuration. The mode register 0x03 is configured for continuous measurement.

Arduino reads the values of the registers 0x03~0x08 and retrieves the magnetic field strengths along the three axes as 16-bit numbers. The values of the registers obtained are in 2’s complement. These raw values are converted to scaled values based on the compass calibration. The scaled values are then computed to calculate the azimuth angle or the compass direction.

Arduino is also interfaced with the SSD1306 OLED as the compass’ graphical display. The screen showcases a compass rose with an arrow direction. The heading direction obtained from the HMC5883L is displayed on the left half of the OLED screen and the arrow indicates the same degrees on the right half of the screen.

The code
The sketch begins by importing the Adafruit_GFX.h and Adafruit_SSD1306.h libraries to work with the OLED display. The Wire.h and HMC5883L.h libraries must also be imported to work with the HMC5883L compass. The HMC5883L library can be downloaded from the Github page.

An object of the HMC5883L class is instantiated and a variable defined to store the compass error. An object of the MagnetometerScaled class is instantiated to calculate the offset along the three axes.

Next, some variables are defined to indicate the SSD1306 OLED’s pin connections. An object of the Adafruit_SSD1306 class is instantiated, specifying the SPI protocol for proper communication with the display. Additional variables are defined to position the compass rose and the direction arrow within the display screen.

The function, compassCalibrate(), is defined for the manual calibration of the HMC5883L compass. Even if the call to this function is commented in the setup() function, the compass will still work with default values for the offsets. This function is used to manually compute the offset values with the help of the Serial Monitor.

In the setup() function, the baud rate for serial communication is set to 9600 bps. The serial communication is used to calibrate the compass with the Serial Monitor. The I2C port is initialized by calling the Wire.begin() method. 

The compass gain is set to +/-1.3 by calling the setScale() method on the compass object. The measurement mode is set to a continuous measurement by calling the setMeasurementMode() method on the compass object. The offset values for the three axes are calculated by calibrating the compass, which is done by calling the compassCalibrate() function. The OLED display is initialized and the position of the compass rose within the screen is set. 

The function Draw_Compass() is defined to draw the compass rose on the OLED display. The function display_direction() is defined to print the directions in the compass rose. The function draw_arrow() is defined to display the direction arrow within the compass rose. 

In the loop() function, the raw values of magnetic strength along the X, Y, and Z axes are obtained by calling the compass.readRawAxis() method. The scaled values are obtained by calling the compass.readScaledAxis() method. 

The scaled values are corrected by the offsets obtained in the compass calibration. The tangent along the YX and ZX planes is, then, calculated. The heading degree in the radian is equal to the magnetic field tangent along the YX plane. The heading degree is adjusted by the declination angle of the current location. 

You can find the declination angle for your location at magnetic-declination.com. For my location, the declination angle is 1˚,2′. When converted to radians, this value is 0.01803. 

The measured heading is adjusted to a value between 0˚ and 360˚. The heading value is in radian, which is converted to degrees. The OLED display is then cleared, and the obtained heading degrees are passed to the variable “angle.” This angle is displayed on the left half of the OLED screen as the heading degrees. The same angle is used to change the position direction arrow and the compass rose and direction arrow are displayed on the right half of the OLED screen.   

The result

https://www.engineersgarage.com/wp-content/uploads/2022/03/P28-DV.mp4

You may also like:


  • Arduino compatible coding 18: Synchronous serial communication using the I2C…

  • How to program an OLED display with Arduino

  • Magnetometer interfacing with Beaglebone black (Part 8/15)

  • OLED Display Technology

  • Led Lighting

  • Computer Monitors : OLED Monitors

Filed Under: Arduino Projects, Electronic Projects, Sensors, Tutorials, Video
Tagged With: Arduino, compass, digital, oled, sensors
 

Next Article

← Previous Article
Next Article →

EE TECH TOOLBOX

“ee
Tech Toolbox: 5G Technology
This Tech Toolbox covers the basics of 5G technology plus a story about how engineers designed and built a prototype DSL router mostly from old cellphone parts. Download this first 5G/wired/wireless communications Tech Toolbox to learn more!

EE Learning Center

EE Learning Center
“engineers
EXPAND YOUR KNOWLEDGE AND STAY CONNECTED
Get the latest info on technologies, tools and strategies for EE professionals.

HAVE A QUESTION?

Have a technical question about an article or other engineering questions? Check out our engineering forums EDABoard.com and Electro-Tech-Online.com where you can get those questions asked and answered by your peers!


RSS EDABOARD.com Discussions

  • BF999 Input and output impedance
  • Control for DC motor
  • Industrial Relay Board Design for Motorcycle Use
  • Sendust vs Ferrite for SMPS
  • On/Off Slide Switch Reassembly Help

RSS Electro-Tech-Online.com Discussions

  • More fun with ws2812 this time XC8 and CLC
  • Wierd makita battery
  • I Wanna build a robot
  • using a RTC in SF basic
  • Is AI making embedded software developers more productive?

Featured – LoRa/LoRaWan Series

  • What is the LoRaWAN network and how does it work?
  • Understanding LoRa architecture: nodes, gateways, and servers
  • Revolutionizing RF: LoRa applications and advantages
  • How to build a LoRa gateway using Raspberry Pi
  • How LoRa enables long-range communication
  • How communication works between two LoRa end-node devices

Recent Articles

  • STMicroelectronics unveils SoC based on secure MCU
  • Nexperia’s 48 V ESD diodes support higher data rates with ultra-low capacitance design
  • Taoglas releases Patriot antenna with 18 integrated elements covering 600 to 6000 MHz
  • Amphenol RF introduces SMPM to SMPM assemblies on RG-178 cable
  • Infineon launches 3D magnetic sensors with ±50 mT to ±160 mT measurement ranges

EE ENGINEERING TRAINING DAYS

engineering

Submit a Guest Post

submit a guest post
Engineers Garage
  • Analog IC TIps
  • Connector Tips
  • Battery Power Tips
  • DesignFast
  • EDABoard Forums
  • EE World Online
  • Electro-Tech-Online Forums
  • EV Engineering
  • Microcontroller Tips
  • Power Electronic Tips
  • Sensor Tips
  • Test and Measurement Tips
  • 5G Technology World
  • Subscribe to our newsletter
  • About Us
  • Contact Us
  • Advertise

Copyright © 2025 WTWH Media LLC. All Rights Reserved. The material on this site may not be reproduced, distributed, transmitted, cached or otherwise used, except with the prior written permission of WTWH Media
Privacy Policy

Search Engineers Garage

  • Electronic Projects & Tutorials
    • Electronic Projects
      • Arduino Projects
      • AVR
      • Raspberry pi
      • ESP8266
      • BeagleBone
      • 8051 Microcontroller
      • ARM
      • PIC Microcontroller
      • STM32
    • Tutorials
      • Audio Electronics
      • Battery Management
      • Brainwave
      • Electric Vehicles
      • EMI/EMC/RFI
      • Hardware Filters
      • IoT tutorials
      • Power Tutorials
      • Python
      • Sensors
      • USB
      • VHDL
    • Circuit Design
    • Project Videos
    • Components
  • Articles
    • Tech Articles
    • Insight
    • Invention Stories
    • How to
    • What Is
  • News
    • Electronic Product News
    • Business News
    • Company/Start-up News
    • DIY Reviews
    • Guest Post
  • Forums
    • EDABoard.com
    • Electro-Tech-Online
    • EG Forum Archive
  • DigiKey Store
    • Cables, Wires
    • Connectors, Interconnect
    • Discrete
    • Electromechanical
    • Embedded Computers
    • Enclosures, Hardware, Office
    • Integrated Circuits (ICs)
    • Isolators
    • LED/Optoelectronics
    • Passive
    • Power, Circuit Protection
    • Programmers
    • RF, Wireless
    • Semiconductors
    • Sensors, Transducers
    • Test Products
    • Tools
  • Learn
    • eBooks/Tech Tips
    • Design Guides
    • Learning Center
    • Tech Toolboxes
    • Webinars & Digital Events
  • Resources
    • Digital Issues
    • EE Training Days
    • LEAP Awards
    • Podcasts
    • Webinars / Digital Events
    • White Papers
    • Engineering Diversity & Inclusion
    • DesignFast
  • Guest Post Guidelines
  • Advertise
  • Subscribe