Turning phone into magnetic compass using Qt mobility project
Article Metadata
Code Example
Article
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
{
public:
Compass(QGraphicsPixmapItem * aItem, QGraphicsScene *Scene, double imageheight);
bool filter(QCompassReading *reading);
~Compass();
private:
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.
Example Applications
Example application was tested with N97 compiled and linked with Nokia Qt Creator. Can be found from following link: File:QtCompasse.zip



Featured article, November 14th 2010 (week 46)