Digital Compass with HMC5883L

Digital Compass with HMC5883L

Introduction

In this experiment, we will use the HMC5883L digital compass sensor to measure the magnetic field and determine the direction. This can be useful for navigation applications.

Digital Compass with HMC5883L

Components Needed

Circuit Setup

  1. Connect the VCC pin of the HMC5883L to the 3.3V pin of the Arduino.
  2. Connect the GND pin to the GND pin of the Arduino.
  3. Connect the SDA pin to A4 and the SCL pin to A5 on the Arduino (for I2C communication).

Ensure all connections are secure and check the orientation of the compass sensor.

HMC5883L Circuit Setup

Code for Digital Compass

Upload the following code to your Arduino to read the magnetic field and determine direction:


#include 
#include 

HMC5883L compass;

void setup() {
  Serial.begin(9600);
  Wire.begin();
  compass.initialize();
}

void loop() {
  Vector norm = compass.readNormalize();
  float heading = atan2(norm.YAxis, norm.XAxis);
  if (heading < 0) {
    heading += 2 * M_PI;
  }
  float headingDegrees = heading * 180/M_PI;
  Serial.println(headingDegrees);
  delay(500);
}
            

Explanation

The HMC5883L uses I2C communication to send magnetic field data to the Arduino. The code processes this data to calculate the heading in degrees and displays it in the Serial Monitor.

Troubleshooting