One thing I’m interested in are the sensors in the N9. This includes the following things:
- Ambient Light Sensor
- Light Sensor
- Orientation Sensor
- Proximity Sensor
- Rotation Sensor
- Tap Sensor
From the list I’m particularly interested in the orientation sensor and the accelerometer as they are very versitile and you can do a lot of things with them.
Starting with sensors
Although there is an overview page of the sensor API containing all the individual sensor classes, it only contains C++ style documentation and examples. There is however a documentation for QML wrappers around the sensor API that you can conviniently use from QML pages directly. This one would be for the orientation sensor.
The QML sensor classes are much just a layers over the regular C++ classes (QSensor). At their core they only one property and one signal:
onReadingChanged: This is a signal that is sent every time the sensors registers a change, for example when the orientation changes.
reading: This property holds the information that was gathered during the last reading. So if you get an onReadingChanged signal, this will hold the new data.
Using the orientation sensor should be easy then: just wait for theonReadingChanged signal and read out the reading property.
The Orientation Sensor
The orientation sensor basically measures which side of your phone is pointing upwards. There are six states the sensor can report:
- TopUp (1)
- TopDown (2)
- LeftUp (3)
- RightUp (4)
- FaceUp (5)
- FaceDown (6)
To start coding, I did again use the standard QML “Hello World” application and removed the button and the label from the MainPage.qml.
All sensor handling is located in QtMobillity, so I started by adding the sensor classes to the project:
import QtMobility.sensors 1.1
Then I added a text field to receive the sensor output:
text: "Orientation starting.."
And finally, I added the sensor:
txtOrientation.text = "Orientation: " + reading.orientation;
And that was it. Note that you actually have to activate the sensor with the “active: true” flag, otherwise it won’t work.
If you compile and run the example you will see the number representing the orientation in the text field. If you want a convinient way of reading out and matching the orientation to states, look at this example.
The accelerometer is a sensor that measures, well, acceleration. So if you would move the phone on the x-plane, you would get a positive x reading (or negative, depending on your direction). Read more about accelerometers here.
All sensors work the same in QML, only the reading is different, so instead of reading.orientation, we ask for x, y and z values.
txtAccelerometer.text = "Accelerometer: \nX: " + reading.x +
"\nY: " + reading.y +
"\nZ: " + reading.z;
And there you go: you can output the readings from the accelerometer.
That is really all there is to work with sensors in QML. I have to say I’m pretty impressed at how easy this was. You can find the source to this example here.