Please note that as of October 24, 2014, the Nokia Developer Wiki will no longer be accepting user contributions, including new entries, edits and comments, as we begin transitioning to our new home, in the Windows Phone Development Wiki. We plan to move over the majority of the existing entries. Thanks for all your past and future contributions.

Turning phone into magnetic compass using Qt mobility project

From Wiki
Jump to: navigation, search
Article Metadata
Code ExampleCompatibility
Created: mahbub_s60 (15 Oct 2010)
Last edited: hamishwillee (11 Oct 2012)
Featured Article
14 Nov

This code snippet shows how we can turn your sensor enabled phone into a compass using Qt Mobility Sensor API (provided it has a sensor that can detect magnetic north!). If you rotate the device the compass is rotated to indicate the north.

How Qt Magnetic Sensor works

We derive a class from QCompassFilter class. QCompassFilter class does not do much it is just a wrapper class around QSensorFilter . QSensorFilter class provides an efficient callback facility for asynchronous notifications of sensor status changes. When a sensor data is changed that is notified by filter method. filter method should return true if it is interested to receive data constantly.

We need QSensor class as a member variable that represent a single hardware sensor. Multiple filters can be added to a sensor. They are called in order and each filter has the option to modify the values in the reading or to suppress the reading altogether. Data rate (Hertz) of the sensor can be set by calling setDataRate if necessary.


Header file of Compass example.

class Compass : public QCompassFilter
Compass(QGraphicsPixmapItem * aItem, QGraphicsScene *Scene, double imageheight);
bool filter(QCompassReading *reading);
qtimestamp stamp;
QGraphicsPixmapItem * m_compassImage;
QGraphicsScene * m_Scene;
double m_imageheight;
int m_rate_val;
QCompass m_sensor;

Get the compass reading and rotate the image.

bool Compass::filter(QCompassReading *reading)
int diff = ( reading->timestamp() - stamp );
stamp = reading->timestamp();
QString str;
str = QString("%1 deg").arg(reading->azimuth(), 3, 'f', 0);
qDebug() << str << endl;
return true;

Example Applications

Example application was tested with N97 compiled and linked with Nokia Qt Creator. Can be found from following link:

Related Article

How to turn the N97 into a Magnetic Compass

This page was last modified on 11 October 2012, at 01:23.
98 page views in the last 30 days.