Raspberry Pi MAG3110 Electronic Compass Sensor Java Tutorial
by Dcube Tech Ventures in Circuits > Electronics
54 Views, 0 Favorites, 0 Comments
Raspberry Pi MAG3110 Electronic Compass Sensor Java Tutorial
MAG3110 is a small, low power, digital 3-axis magnetometer. Its sensitivity is very high as well as it is embodied with an efficient noise reduction mechanism. It requires very low power for its efficient operation and works in single-shot measurement mode. Here is the demonstration with a python code using Raspberry Pi.
What You Need..!!
Connection:
Take a I2C shield for raspberry pi and gently push it over the gpio pins of raspberry pi.
Then connect the one end of I2C cable to MAG3110 sensor and the other end to the I2C shield.
Also connect the Ethernet cable to the pi or you can use a WiFi module.
Connections are shown in the picture above.
Code:
The java code for MAG3110 can be downloaded from our github repository- Dcube Store
Here is the link for the same :
https://github.com/DcubeTechVentures/MAG3110/blob/master/Java/MAG3110.java
We have used pi4j library for java code, the steps to install pi4j on raspberry pi is described here:
You can also copy the code from here, it is given as follows:
// Distributed with a free-will license.
// Use it any way you want, profit or free, provided it fits in the licenses of its associated works.
// MAG3110
// This code is designed to work with the MAG3110_I2CS I2C Mini Module .
import com.pi4j.io.i2c.I2CBus;
import com.pi4j.io.i2c.I2CDevice;
import com.pi4j.io.i2c.I2CFactory;
import java.io.IOException;
public class MAG3110
{
public static void main(String args[]) throws Exception
{
// Create I2C bus
I2CBus bus = I2CFactory.getInstance(I2CBus.BUS_1);
// Get I2C device, MAG3110 I2C address is 0x0E(14)
I2CDevice device = bus.getDevice(0x0E);
// Send Start Command , Active mode
device.write(0x10,(byte)0x01);
Thread.sleep(200);
// Read 6 bytes of data from address 0x01(1) , msb first
byte[] data = new byte[6];
device.read(0x01,data,0,6);
// Convert data
int xMag = (((data[0] & 0xFF) * 256 ) + (data[1] & 0xFF));
if(xMag > 32767)
{
xMag -= 65536;
}
int yMag = (((data[2] & 0xFF) * 256 ) + (data[3] & 0xFF));
if(yMag > 32767)
{
yMag -= 65536;
}
int zMag = (((data[4] & 0xFF) * 256 ) + (data[5] & 0xFF));
if(zMag > 32767)
{
zMag -= 65536;
}
// Output data to screen
System.out.printf("Magnetic field in X Axis : %d %n" , xMag);
System.out.printf("Magnetic field in Y Axis : %d %n" , yMag);
System.out.printf("Magnetic field in Z Axis : %d %n" , zMag);
}
}
Applications:
MAG3110 is a small, low power, digital 3-axis magnetometer. It can be employed in electronic compass and location based services which includes Smartphones, personal navigation devices, robotics, UAVs, speed sensing, current sensing and wrist watches with embedded electronic compasses (e-compass) function.