
#include <SparkFun_MAG3110.h>
MAG3110 mag = MAG3110(); //Instantiate MAG3110
void setup() {
Serial.begin(9600);
mag.initialize(); //Initializes the mag sensor
mag.start(); //Puts the sensor in active mode
}
void loop() {
int x, y, z;
//Only read data when it's ready
if(mag.dataReady()) {
//Read the data
mag.readMag(&x, &y, &z);
Serial.print("X: ");
Serial.print(x);
Serial.print(", Y: ");
Serial.print(y);
Serial.print(", Z: ");
Serial.println(z);
Serial.println("--------");
}
}
Calling
mag.initialize()
sets up the sensor and checks whether a MAG3110 is connected properly. If
mag.error
is true, the Arduino was unable to talk to the
MAG3110! When initialized, the magnetometer is set to standby mode with all offsets set to 0. To put the magnetometer in active mode and start sampling, simply
write
mag.start()
You can check whether any new data is ready using the
mag.dataReady()
function. This will return true if new data is available.
You can read all three axes using the
mag.readMag()
function. Don’t be afraid of the & symbol! This simply means we are giving the address of the variables to the
function so that they can be filled with the data. If this seems confusing, you might want to read about pointers.
If you run this sketch and open up Tools->Serial Monitor, you should see the following:
Other functions can be seen in the
SparkFun-MAG3110-Other.ino
sketch: