]> git.piffa.net Git - sketchbook_andrea/blob - hardware/bussola/hmc5883l_i2c/hmc5883l_i2c.ino
bussola
[sketchbook_andrea] / hardware / bussola / hmc5883l_i2c / hmc5883l_i2c.ino
1 /*
2 An Arduino code example for interfacing with the HMC5883
3
4 by: Jordan McConnell
5  SparkFun Electronics
6  created on: 6/30/11
7  license: OSHW 1.0, http://freedomdefined.org/OSHW
8
9 Analog input 4 I2C SDA
10 Analog input 5 I2C SCL
11
12 Link: https://www.sparkfun.com/tutorials/301
13 Datasheet e registri: http://dlnmh9ip6v2uc.cloudfront.net/datasheets/Sensors/Magneto/HMC5883L-FDS.pdf
14 */
15
16 #include <Wire.h> //I2C Arduino Library
17
18 #define address 0x1E //0011110b, I2C 7bit address of HMC5883
19
20 void setup(){
21   //Initialize Serial and I2C communications
22   Serial.begin(9600);
23   Wire.begin();
24   
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();
32 }
33
34 void loop(){
35   
36   int x,y,z; //triple axis data
37
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();
42   
43  
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
53   }
54   
55   //Print out values of each axis
56   Serial.print("x: ");
57   Serial.print(x);
58   Serial.print("  y: ");
59   Serial.print(y);
60   Serial.print("  z: ");
61   Serial.print(z);
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
66 }
67   
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);
73   
74   delay(250);
75 }