Sensor utilities (sensor.h)

Functions and structures to control sensors.

This file contains the interface to the sensor service.

The following are the available sensors and their corresponding file paths. Not all sensors are available on all systems; use access() to determine the existence of a sensor.

Sensor Type Sensor Path
Accelerometer /dev/sensor/accel
Magnetometer /dev/sensor/mag
Gyroscope /dev/sensor/gyro
Altimeter /dev/sensor/alt
Temperature /dev/sensor/temp
Proximity /dev/sensor/prox
Light /dev/sensor/light
Gravity /dev/sensor/gravity
Linear Acceleration /dev/sensor/linAccel
Rotation Vector /dev/sensor/rotVect
Orientation /dev/sensor/orientation
Rotation Matrix /dev/sensor/rotMatrix
Azimuth, Pitch and Roll /dev/sensor/apr
Face Detect /dev/sensor/faceDetect
Pressure /dev/sensor/pressure
Holster /dev/sensor/holster
Compass /dev/sensor/compass

This file also defines device-specific commands (e.g., DCMD_SENSOR_SKIPDUPEVENT) that are used with calls to devctl() to control the sensors.

The following example demonstrates using elements from sensor.h to read the accelerometer sensor:
void sensor_read(void)
    const char* sensor_path = "/dev/sensor/accel";
    sensor_event_t se;
    int len = 0;

    // Check if this system contains the specified sensor.
    int rc = access(sensor_path, F_OK);
    if (-1 == rc) {
        fprintf(stderr, "error(%s) accessing path(%s)\n", strerror(errno),

    // Open the sensor with read only access.
    // Leave the default for blocking read.
    int fd = open(sensor_path, O_RDONLY);
    if (-1 == fd) {
        fprintf(stderr, "error(%s) opening path(%s)\n", strerror(errno),

    // Send the skip duplicate event device control.
    // The device must be moved for a new event to be sent.
    sensor_devctl_skipdupevent_u a_devctl;
    memset(&a_devctl, 0, sizeof(a_devctl));
    a_devctl.tx.enable = 1;
    rc = devctl(fd, DCMD_SENSOR_SKIPDUPEVENT, &a_devctl, sizeof(a_devctl),
    if (EOK != rc) {
        fprintf(stderr, "error(%s) attempting to skip duplicates\n",

    // Start an infinite loop.
    for (;;) {
        memset(&se, 0, sizeof(se));

        // Block waiting for new sensor data.
        len = read(fd, &se, sizeof(se));

        // Check for errors.
        if (-1 == len) {
            fprintf(stderr, "read error(%s)\n", strerror(errno));
        if (len < sizeof(se)) {
            fprintf(stderr, "read size(%d) less then expected(%d)", len,
        if (SENSOR_TYPE_ACCELEROMETER != se.type) {
            fprintf(stderr, "received type(%d) different then expected(%d)",
                    se.type, SENSOR_TYPE_ACCELEROMETER);

        // Print out the payload by indexing into common structure.
        fprintf(stdout, "Acceleration->\tx:%+.2f\ty:%+.2f\tz:%+.2f\n",
                se.motion.dsp.x, se.motion.dsp.y, se.motion.dsp.z);

Last modified: 2014-05-14

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

comments powered by Disqus