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
17 #include <common.h> //Libreria comune
19 #define address 0x1E //0011110b, I2C 7bit address of HMC5883
21 const byte redPin = 11; // 2v a 20ma: che resistenza dovro usare?
22 const byte greenPin = 10; // 3.5v a 20ma: che resistenza dovro usare?
23 const byte bluePin = 9; // 3.5v a 20ma: che resistenza dovro usare?
26 //Initialize Serial and I2C communications
30 //Put the HMC5883 IC into the correct operating mode
31 Wire.beginTransmission(address); //open communication with HMC5883
32 Wire.write(0x00); //select mode Measurement Configuration Bits
33 Wire.write(0x70); // 8 -average, 15 Hz default, normal measuremen
34 Wire.write(0x02); //select mode register
35 Wire.write(0x00); //continuous measurement mode
36 Wire.endTransmission();
38 // Cambiare la modalita' di lavoro in Single-Measurement Mode
39 // e farlo leggere ogni ~20ms / 3hz di lettura
40 // Default 15hz = 4ms ; 67ms consigliati
41 // Tra una lettura e l'altra va' in standby
43 pinMode(redPin, OUTPUT);
44 pinMode(greenPin, OUTPUT);
45 pinMode(bluePin, OUTPUT);
50 int x, y, z ; //triple axis data
52 //Tell the HMC5883 where to begin reading data
53 Wire.beginTransmission(address);
54 Wire.write(0x03); //select register 3, X MSB register
55 Wire.endTransmission();
58 //Read data from each axis, 2 registers per axis
59 Wire.requestFrom(address, 6);
60 if (6 <= Wire.available()) {
61 x = Wire.read() << 8; //X msb
62 x |= Wire.read(); //X lsb
63 z = Wire.read() << 8; //Z msb
64 z |= Wire.read(); //Z lsb
65 y = Wire.read() << 8; //Y msb
66 y |= Wire.read(); //Y lsb
68 float radianti = atan2(x, y) ;
69 if (radianti < 0) {// Se y e'antiorario il segno e' inverso
70 radianti += 2 * PI ; // inverte il segno
73 //float gradi = radianti * 180 / PI; // Conversione in gradi
74 // gradi += 2.56 ; // Correzione per la declinazione magnetica locale
75 // Modena dovrebbe essere a +2° 34' positivi EST
78 //xval = cos(map(radianti, 0, 2 * PI, 0, 255));
79 xval = lum(255 - (127 + 127 * (cos(radianti))));
80 analogWrite(redPin, 0); // Common anodo
81 analogWrite(bluePin, 255 - xval);
82 analogWrite(greenPin, 255 - xval);
86 //Print out values of each axis
89 Serial.print(" radianti: ");
90 Serial.print(cos(radianti));
91 Serial.print(" redval: ");