Magnetometer

A magnetometer measures the strength of the magnetic field in three dimensions.

The magnetometer sensor returns magnetic flux density values in microteslas (µT). These values are processed to compensate for local interference, and provide data based on the Earth's magnetic field.

A BPS event with the code SENSOR_MAGNETOMETER_READING is generated when new magnetometer values are available. You can call the function sensor_event_get_xyz() to retrieve the magnetic field values from the event.

The code sample below demonstrates how you can use the magnetometer sensor in your app:

#include <stddef.h>
#include <bps/bps.h>
#include <bps/sensor.h>

int main(void)
{
    int event_domain;
    unsigned int event_code;

    // Create variables to store magnetometer sensor readings.
    float x_magflux, y_magflux, z_magflux;

    bps_initialize();

    if (sensor_is_supported(SENSOR_TYPE_MAGNETOMETER))
    {
        sensor_request_events(SENSOR_TYPE_MAGNETOMETER);
    }

    while (1)
    {
        bps_event_t *current_event = NULL;
        bps_get_event(&current_event, -1);

        event_domain = bps_event_get_domain(current_event);
        event_code = bps_event_get_code(current_event);

        if (event_domain == sensor_get_domain())
        {
            switch (event_code)
            {
                case SENSOR_MAGNETOMETER_READING:
                    // Get the current magnetic flux density values.
                    sensor_event_get_xyz(current_event, 
                                         &x_magflux, 
                                         &y_magflux, 
                                         &z_magflux);
                    // Update program based on current magnetic
                    // flux values.
                    break;

                default:
                    break;
            }
        }
    }

    // Program cleanup
    sensor_stop_events(SENSOR_TYPE_MAGNETOMETER);
    bps_shutdown();
    return 0;
}                
            

Last modified: 2013-12-21



Got questions about leaving a comment? Get answers from our Disqus FAQ.

comments powered by Disqus