Find the north

boussole_bb

Parts :

– 1 x Arduino nano

– 1 x led

– 1x R 220 Ω

– 1 x HMC5883L module


#include //I2C Arduino Library

#define address 0x1E //0011110b, I2C 7bit address of HMC5883
int LED = 6;
float direction;

void setup(){
//Initialize Serial and I2C communications
Serial.begin(9600);
Wire.begin();

//Put the HMC5883 IC into the correct operating mode
Wire.beginTransmission(address); //open communication with HMC5883
Wire.write(0x02); //select mode register
Wire.write(0x00); //continuous measurement mode
Wire.endTransmission();
pinMode(LED,OUTPUT);
}

void loop(){

int x,y,z; //triple axis data

//Tell the HMC5883L where to begin reading data
Wire.beginTransmission(address);
Wire.write(0x03); //select register 3, X MSB register
Wire.endTransmission();

//Read data from each axis, 2 registers per axis
Wire.requestFrom(address, 6);
if(6<=Wire.available()){ x = Wire.read()<<8; //X msb x |= Wire.read(); //X lsb z = Wire.read()<<8; //Z msb z |= Wire.read(); //Z lsb y = Wire.read()<<8; //Y msb y |= Wire.read(); //Y lsb } //Print out values of each axis Serial.print("x: "); Serial.print(x); Serial.print(" y: "); Serial.print(y); Serial.print(" z: "); Serial.println(z); if ( y > 0 )
{
direction= 90 - atan2(y,x)*180.0/PI;
}
else
{
direction= 270 - atan2(y,x)*180.0/PI;
}
Serial.print("direction: ");
Serial.print(direction);
delay(250);

if (abs(direction)<20) { digitalWrite(LED, HIGH); Serial.print("Switch on led"); } else { digitalWrite(LED, LOW); } }