sensor-experiments

Objective

This experiment uses the HMC5883L magnetometer sensor to detect the direction of magnetic fields and measure compass headings.

Components Required

No Ads Available.

Working Principle

The HMC5883L sensor detects the magnetic field strength along three axes (X, Y, and Z). The readings are processed by the Arduino to calculate the heading.

Code

/*
 * Compass Reading with HMC5883L
 * This code reads the magnetic field values from the HMC5883L sensor and calculates the heading.
 */

#include 
#include 

HMC5883L compass;

void setup() {
  Serial.begin(9600);  // Initialize serial communication
  Wire.begin();
  compass.initialize();
}

void loop() {
  Vector norm = compass.readNormalize();
  
  float heading = atan2(norm.YAxis, norm.XAxis);
  if (heading < 0) {
    heading += 2 * PI;
  }
  heading = heading * 180 / PI;
  
  Serial.print("Heading: ");
  Serial.println(heading);
  
  delay(1000);  // Wait for 1 second before the next reading
}
            

Results

The serial monitor will display the heading in degrees (0 to 360) based on the detected magnetic field.

Applications

Contact Us

If you have any questions or inquiries, feel free to reach out to us at Microautomation.no@icloud.com .

Follow our Socials for the newest updates!