ElectroPeak
Published © GPL3+

Make a Digital Compass w/ GY-511 Accelerometer/Magnetometer

In this tutorial, you’ll learn how to use the LSM303DLHC GY-511 compass module with Arduino to make a digital compass.

BeginnerProtip1 hour37,109
Make a Digital Compass w/ GY-511 Accelerometer/Magnetometer

Things used in this project

Hardware components

Arduino UNO R3
×1
GY-511 3-Axis Accelerometer + Magnetometer
×1
TowerPro Servo Motor SG-90
×1
1602 LCD Module
×1
ElectroPeak Jumpers
×1

Software apps and online services

Arduino IDE
Arduino IDE

Story

Read more

Code

code 1

Arduino
/*   
Compass Calibration
by Hanie Kiani 
https://electropeak.com/learn/ 
*/ 
#include <Wire.h>
#include <LSM303.h>

LSM303 compass;
LSM303::vector<int16_t> running_min = {32767, 32767, 32767}, running_max = {-32768, -32768, -32768};

char report[80];

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

void loop() {  
  compass.read();
  
  running_min.x = min(running_min.x, compass.m.x);
  running_min.y = min(running_min.y, compass.m.y);
  running_min.z = min(running_min.z, compass.m.z);

  running_max.x = max(running_max.x, compass.m.x);
  running_max.y = max(running_max.y, compass.m.y);
  running_max.z = max(running_max.z, compass.m.z);
  
  snprintf(report, sizeof(report), "min: {%+6d, %+6d, %+6d}    max: {%+6d, %+6d, %+6d}",
    running_min.x, running_min.y, running_min.z,
    running_max.x, running_max.y, running_max.z);
  Serial.println(report);
  
  delay(100);
}
  compass.init();
  compass.enableDefault();

code 2

Arduino
/*   
Compass Calibration
by Hanie Kiani 
https://electropeak.com/learn/ 
*/ 
#include <Wire.h>
#include <LSM303.h>
#include <Servo.h>
LSM303 compass;
int servoPin = 3; 
Servo Servo1; 
void setup() {
  Serial.begin(9600);
  Wire.begin();
  Servo1.attach(servoPin); 
  compass.init();
  compass.enableDefault();
  

  compass.m_min = (LSM303::vector<int16_t>){-32767, -32767, -32767};
  compass.m_max = (LSM303::vector<int16_t>){+32767, +32767, +32767};
}

void loop() {
  compass.read();
  

  float heading =compass.heading((LSM303::vector<int>){0, 0, 1});
  
  Serial.println(heading);
  Servo1.write(180-heading);
  delay(100);
}

Credits

ElectroPeak
57 projects • 742 followers
At ElectroPeak we want to teach you to enjoy electronics more. We offer Top-notch guides and worry-free shopping experience.
Contact

Comments

Please log in or sign up to comment.