German English
Sensors

HMC5883L - Read magnetic field sensor values

The microcontroller on the radio module Preon32 has several IO interfaces which allows accessing nearly each kind of sensor. The product VariSen which is designed for use with Preon32 contains some sensors, the HMC5883L included.

This examples shows how to access a HMC5883L sensor via the I2C interface. The program reads the magnetic field sensor values each second and prints it out. Accessing this sensor is very easy because Virtenio provides a driver for it.
/*
 * Copyright (c) 2011., Virtenio GmbH
 * All rights reserved.
 */
package com.virtenio.webdemo.sensor;

import com.virtenio.drivers.i2c.NativeI2C;
import com.virtenio.drivers.sensors.i2c.HMC5883L;

import java.io.IOException;

public class DigiMagI2C {

    public static void main(String[] args) throws IOException, InterruptedException {

        // open Native I2C Bus
        NativeI2C i2c = NativeI2C.getInstance(1);
        i2c.open();

        // initialise HMC5883L sensor
        HMC5883L digitalMagSensor = new HMC5883L(i2c);
        digitalMagSensor.setMode(HMC5883L.MODE_CONTINUOUS);
        digitalMagSensor.configure(
                HMC5883L.SAMPLES_AVERAGED_8,    // 8 Samples per measurement
                HMC5883L.DATA_RATE_15,          // Data output rate of 15 Hz
                HMC5883L.MODE_CONTINUOUS,       // Continuous measurement mode
                7   // gain
        );

        while (true) {
            // capture measured value every 1000ms
            short[] ch = new short[3];
            int offset = 0;
            digitalMagSensor.readValues(ch, offset);
            System.out.println("DigiMag " +
                               "CH[0]:" + ch[0] + " " +
                               "CH[1]:" + ch[1] + " " +
                               "CH[2]:" + ch[2]);
            Thread.sleep(1000);
        }
    }
}