@@ -35,16 +35,18 @@ MAG3110::MAG3110() {
35
35
y_scale = 0 .0f ;
36
36
}
37
37
38
- void MAG3110::initialize () {
38
+ bool MAG3110::initialize () {
39
39
Wire.begin ();
40
+ Wire.setClock (400000 ); // I2C fast mode, 400kHz
40
41
if (readRegister (MAG3110_WHO_AM_I) != MAG3110_WHO_AM_I_RSP){ // Could not find MAG3110
41
42
// Serial.println("Could not find MAG3110 connected!");
42
- error = true ;
43
+ return false ;
43
44
}
44
45
else // Successfully initialized
45
46
{
46
47
// Initial values
47
48
reset ();
49
+ return true ;
48
50
}
49
51
}
50
52
@@ -78,18 +80,43 @@ bool MAG3110::dataReady() {
78
80
}
79
81
80
82
void MAG3110::readMag (int * x, int * y, int * z){
81
- // Read each axis
82
- *x = readAxis (MAG3110_OUT_X_MSB);
83
- *y = readAxis (MAG3110_OUT_Y_MSB);
84
- *z = readAxis (MAG3110_OUT_Z_MSB);
83
+
84
+ // Start readout at X MSB address
85
+ Wire.beginTransmission (MAG3110_I2C_ADDRESS);
86
+ Wire.write (MAG3110_OUT_X_MSB);
87
+ Wire.endTransmission ();
88
+
89
+ delayMicroseconds (2 );
90
+
91
+ // Read out data using multiple byte read mode
92
+ Wire.requestFrom (MAG3110_I2C_ADDRESS, 6 );
93
+ while ( Wire.available () != 6 ) {}
94
+
95
+ // Combine registers
96
+ uint16_t values[3 ];
97
+ for (uint8_t idx = 0 ; idx <= 2 ; idx++)
98
+ {
99
+ values[idx] = Wire.read () << 8 ; // MSB
100
+ values[idx] |= Wire.read (); // LSB
101
+ }
102
+
103
+ // Put data into referenced variables
104
+ *x = (int ) values[0 ];
105
+ *y = (int ) values[1 ];
106
+ *z = (int ) values[2 ];
107
+
85
108
}
86
109
87
110
void MAG3110::readMicroTeslas (float * x, float * y, float * z){
88
111
112
+ // Using internal read function
113
+ int x_int, y_int, z_int;
114
+ readMag (&x_int, &y_int, &z_int);
115
+
89
116
// Read each axis and scale to Teslas
90
- *x = (float ) readAxis (MAG3110_OUT_X_MSB) * 0 .1f ;
91
- *y = (float ) readAxis (MAG3110_OUT_Y_MSB) * 0 .1f ;
92
- *z = (float ) readAxis (MAG3110_OUT_Z_MSB) * 0 .1f ;
117
+ *x = (float ) x_int * 0 .1f ;
118
+ *y = (float ) y_int * 0 .1f ;
119
+ *z = (float ) z_int * 0 .1f ;
93
120
94
121
}
95
122
@@ -316,6 +343,6 @@ int MAG3110::readAxis(uint8_t axis){
316
343
317
344
lsb = readRegister (lsbAddress);
318
345
319
- int out = (lsb | (msb << 8 )); // concatenate the MSB and LSB
320
- return out;
346
+ int16_t out = (lsb | (msb << 8 )); // concatenate the MSB and LSB;
347
+ return ( int ) out;
321
348
}
0 commit comments