2 An Arduino code example for interfacing with the HMC5883
7 license: OSHW 1.0, http://freedomdefined.org/OSHW
10 Analog input 5 I2C SCL
12 Link: https://www.sparkfun.com/tutorials/301
13 Datasheet e registri: http://dlnmh9ip6v2uc.cloudfront.net/datasheets/Sensors/Magneto/HMC5883L-FDS.pdf
16 #include <Wire.h> //I2C Arduino Library
18 #define address 0x1E //0011110b, I2C 7bit address of HMC5883
21 //Initialize Serial and I2C communications
25 //Put the HMC5883 IC into the correct operating mode
26 Wire.beginTransmission(address); //open communication with HMC5883
27 Wire.write(0x00); //select mode Measurement Configuration Bits
28 Wire.write(0x70); // 8 -average, 15 Hz default, normal measuremen
29 Wire.write(0x02); //select mode register
30 Wire.write(0x00); //continuous measurement mode
31 Wire.endTransmission();
36 int x,y,z; //triple axis data
38 //Tell the HMC5883 where to begin reading data
39 Wire.beginTransmission(address);
40 Wire.write(0x03); //select register 3, X MSB register
41 Wire.endTransmission();
44 //Read data from each axis, 2 registers per axis
45 Wire.requestFrom(address, 6);
46 if(6<=Wire.available()){
47 x = Wire.read()<<8; //X msb
48 x |= Wire.read(); //X lsb
49 z = Wire.read()<<8; //Z msb
50 z |= Wire.read(); //Z lsb
51 y = Wire.read()<<8; //Y msb
52 y |= Wire.read(); //Y lsb
55 //Print out values of each axis
62 // Calcolo cotangente per gradi: https://it.wikipedia.org/wiki/Arcotangente2
63 float radianti = atan2(x,y) ;
64 if (radianti < 0) {// Se y e'antiorario il segno e' inverso
65 radianti += 2 * PI ; // inverte il segno
68 float gradi = radianti * 180 / PI; // Conversione in gradi
69 gradi += 2.56 ; // Correzione per la declinazione magnetica locale
70 // Modena dovrebbe essere a +2° 34' positivi EST
71 Serial.print(" gradi: ");
72 Serial.println(gradi);