Thursday, April 29, 2010

The HTG G Sensor

Here is a very simple application that illustrates how to use the HTC G Sensor. This is included in a number of devices (including my own HTC Touch Pro) and it provides a way to determine the spatial position of the phone by providing "tilt" values for the X, Y and Z coordinate axis.

Although HTC did not provide a public API for the G Sensor (shame on them for this), Scott Seligman reverse engineered it which eventually led to a Codeplex project on this subject. The code you see here was ported from the C# version of the Codeplex project back to C++.

The application is quite simple: it merely connects to the G Sensor data source, samples it every 200 ms and displays the tilt values on the screen. As usual, I used WTL to write this simple app and its main features are:
  • The HTCGSensor class that implements an interface to the HTC G Sensor API;
  • The view window (CHtcSensorView) that samples the G Sensor data every 200 milliseconds and displays the tilt values;
  • The frame window (CHtcSensorFrame) where the sampling timer is started (see the OnCreate handler)
The HTCGSensor class has a few points worth noticing: the sensor DLL is dynamically linked through the LoadLibrary API and the data reading function pointer is cached for better performance. Note that access to the sensor data requires acquiring a handle so, proper finalization is required.

Sample code: HtcSensor.zip

The sample application requires an HTC device with a G Sensor like the Diamond. You can use this information in a number of different ways on the device. On a forthcoming post, I will show how you can consume this information on a desktop .NET 3.5 application.

No comments:

Post a Comment