This article is a detailed guide on how to implement sensors on an Ultrabook® running Windows 8. There are many sensors on the Ultrabook®, but this demo will only use the accelerometer. The article will be using a demo application to help explain the details. To fully comprehend this article, please review the requirements before continuing.
1. MSDN Account: http://msdn.microsoft.com/en-us/ms348103.aspx
2. Windows 8: http://windows.microsoft.com/en-US/windows-8/release-preview
3. Visual Studio 2012 : http://www.microsoft.com/visualstudio/11/en-us/downloads
4. Ultrabook with touch screen enabled and sensors enabled
5. Programming knowledge of XAML
6. Programming knowledge of C#
Compiling the project
1. Unzip the source code and locate the solution: Win8Demo.sln
2. Compile the project in Visual Studio 2012 and run it in debug mode
3. Verify that the solution compiles successfully and run the app:
Implementing the sensor demo
We will begin by examining the senor example. Please take a moment to run the sensor example and get familiar with the user interface. Press the Start Accelerometer button and pick up the Ultrabook®. As the move the device, observe the ball bounce around the screen. Also notice the xyz coordinate change as the ball is moved.
The accelerometer is not end user event driven like the touch demo. Image only moved when the user touched the screen. In this demo, once the [Start Accelerometer] button is pressed, data is constantly being streamed to the screen. There are timers that forces events to be executed.
Open the source code project now and examine the XAML file:AccelerometerText.XAML
Notice the Grid tag, there is where we define the ball, the Ellipse tag is used to create the ball. We also set the size and color. Unlike the touch demo, there is no accelerometer event handlers placed here. The canvas is only used to display the results of the accelerometer readings.
Open the file: AccelerometerTest.cs
The demo begins the moment the [Start Accelerometer] button is pressed. This calls the function SetAcc. This initialization function creates to two timers: drawing and accelerometer data updates.
The drawing timer (m_timer) updates the circle every 20 milliseconds. That can be seen at the bottom of the function. Every 20 milliseconds, the canvas will automatically draw the location of the ball based on the streaming xyz data updates from the top left and corner. The accelerometer data update timer (acc_monitor) will post the accelerometer xyz data ever 50 milliseconds. This is defined by the acc_monitor.update function. We look at this feature later in the tutorial. These two times must work together to make a smooth movement across the screen. Posting too often or to slowly can make the ball move erratically. Also, drawing too often will take up too much resource and slow the device.
Also notice the acc_monitor.stateChanged event, this actually starts and stops the timer.