summaryrefslogtreecommitdiff
path: root/debug/IMU_comp/IMU_comp.ino
blob: 0c3928d90c6c891279fd1fc8ded22f91cd878bb7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <Wire.h>
#include <LIS3MDL.h>
#include <math.h>

LIS3MDL mag;

void setup()
{
  Serial.begin(9600);
  Wire.begin();

  if (!mag.init())
  {
    Serial.println("Failed to detect and initialize magnetometer!");
    while (1);
  }

  mag.enableDefault();
}

void loop()
{
  mag.read();

  // Calculate heading
  float heading = atan2(mag.m.y, mag.m.x);
  if (heading < 0)
    heading += 2 * PI; // Normalize heading to positive angles

  // Convert from radians to degrees
  float headingDegrees = heading * 180.0 / PI;

  // Adjust for magnetic declination if needed
  // headingDegrees += magneticDeclination;

  // Normalize headingDegrees to [0, 360) range
  if (headingDegrees >= 360.0)
    headingDegrees -= 360.0;

  // Print heading
  Serial.print("Heading: ");
  Serial.println(headingDegrees);

  delay(100);
}