Introduction

The electronic compass is designed to detect the earth’s magnetic field and provide magnetic heading data to a microcontroller like Arduino. The one we’ll be using today is the GY-271 module, based on the HMC5883L sensor.

Equipped with a Hall-effect sensor, the GY-271 offers reasonable accuracy for measuring magnetic orientation. It incorporates a three-axis system that detects variations in the magnetic field on the X, Y and Z axes. This data can be used to determine the direction in which the module is oriented in relation to magnetic north.

  • GY-271 compass pins

  • Vcc : To be connected to the 3.3V of the Arduino board
  • GND : Connect to Arduino board ground
  • SDA : Connect to pin A4 of analog outputs
  • SCL: Connect to pin A5 of analog outputs

Electronic schematic

Here’s the circuit diagram for connecting the GY-271. It uses the i2C of the Arduino board:

Programming

 

To download the program for the GY-271 compass you’ll need to install the adafruit library for the HMC5883, which is the chip that controls our compass:

#include <Wire.h> //I2C Arduino Librairie
#define HMC5883L_ADDR 0x1E //addresse i2c du HMC5883
bool haveHMC5883L = false ;

bool detectHMC5883L () {
 Wire.beginTransmission(HMC5883L_ADDR) ; 
Wire.write(10) ; 
Wire.endTransmission() ;
 Wire.requestFrom(HMC5883L_ADDR, 3) ;
if(3 == Wire.available())) {
 char a = Wire.read() ;
 char b = Wire.read() ;
 char c = Wire.read() ;
if(a == 'H' && b == '4' && c == '3')
 return true ;
}
 return false ;
}
void setup() {
 //On initialise le moniteur série et l'i2C
 Serial.begin(9600) ;
 Serial.println("Démarrage") ;
 Wire.begin() ;
 TWBR = 78 ; 
TWSR |= _BV (TWPS0) ; 
}
void loop() {
bool detect = detectHMC5883L() ;
if(!haveHMC5883L) {
 if(detect) {
 haveHMC5883L = true ;
 Serial.println("La boussole est détectée") ;
 Wire.beginTransmission(HMC5883L_ADDR) ; 
Wire.write(0x02) ; 
Wire.write(0x00) ; 
Wire.endTransmission() ;
}
else {
 Serial.println("Boussole non detecte") ;
 delay(2000) ;
retour ;
}

}
else {
if(!detect) {
 haveHMC5883L = false ;
 Serial.println("Connexion perdue") ;
 delay(2000) ;
retour ;
}
}
int x,y,z ; //axes du triangle
Wire.beginTransmission(HMC5883L_ADDR) ;
Wire.write(0x03) ; 
Wire.endTransmission() ;
Wire.requestFrom(HMC5883L_ADDR, 6) ;
if(6<=Wire.available()){
 x = Wire.read()<<8 ; 
x |= Wire.read() ; 
z = Wire.read()<<8 ; 
z |= Wire.read() ; 
y = Wire.read()<<8 ; 
y |= Wire.read() ; 
}

Serial.print("x : ") ;
Serial.print(x) ;
Serial.print(" y : ") ;
Serial.print(y) ;
Serial.print(" z : ") ;
Serial.println(z) ;
delay(250) ;
}