31 Days of Windows 8 | Day #26: Gyrometer

This article is Day #26 in a series called 31 Days of Windows 8.  Each of the articles in this series will be published for both HTML5/JS and XAML/C#. You can find additional resources, downloads, and source code on our website.logo

As a kid I was always amazed at a gyroscope. I would find anything I could to balance that thing on. I always though physics was very interesting but like anything if you don’t constantly use it, you start to forget bit’s and pieces of it. As we’ve seen over the past few days, the machines of today have started to become an interesting physics experiment. Rather than just some toy of days past we can leverage these sensors to accomplish some very interesting features.

Today, we are taking a look at yet another sensor that we might find in a Windows 8 device: the gyrometer.  The gyrometer measures the angular velocity or rotational motion. The gyrometer can easily compliment the accelerometer to create one very advanced game controller. When used together, the accelerometer measuring the linear motion and the gyrometer measuring the rotational force, you can make things like a pretty wicked game controller.

Working with the gyrometer is the same as working with our other sensors. Just a few simple steps and we’re getting data:

  • Initialize the Sensor.
  • If it’s available,
    • create a readingchanged event handler.
    • In the event handlers, grab the data from the sensor and write it to the screen.

Here’s my the entirety of my code and it looks scary similar to that of the other sensors.

    var _x, _y, _z;

    function onReadingChanged(e) {
        _x.innerText = e.reading.angularVelocityX.toFixed(2);
        _y.innerText = e.reading.angularVelocityY.toFixed(2);
        _z.innerText = e.reading.angularVelocityZ.toFixed(2);
    }

    function onShaken(e) {
        _wasShaken.innerText = e.timestamp;
    }

    function getDomElements() {
        _x = document.querySelector("#x");
        _y = document.querySelector("#y");
        _z = document.querySelector("#z");
    }

    function startAccelerometer() {
        var gyro = Windows.Devices.Sensors.Gyrometer.getDefault()

        if (gyro) {
            var minimumReportInterval = gyro.minimumReportInterval;
            var reportInterval = minimumReportInterval > 16 ? minimumReportInterval : 25;
            gyro.reportInterval = reportInterval;

            gyro.addEventListener("readingchanged", onReadingChanged);
        }

    }

Once again, no real surprises here. We get to our data in the same basic was as we did with the other sensors. The real magic is your software that leverages the data it’s measuring.

Summary

Today we briefly looked at getting data from our gyrometer. Working with each of these sensors is pretty much the same but what you do with them is entirely up to you.

If you’d like to download my working sample that uses the code from this article, click the icon below:

 downloadHTML

Tomorrow, we’re going to look at the Inclinometer.  See you then!

downloadTheTools

Posted in 31 Days, Windows 8 | Tagged , | 1 Comment

31 Days of Windows 8 | Day #25: Accelerometer

This article is Day #25 in a series called 31 Days of Windows 8.  Each of the articles in this series will be published for both HTML5/JS and XAML/C#. You can find additional resources, downloads, and source code on our website.

advertisementsample

Today, we are taking a look at another sensor that we might find in a Windows 8 device: the accelerometer.  With the accelerometer, we can measure the movement of the user’s machine. If you’re looking for more information about what exactly an accelerometer is check out this. With an accelerometer we can do things like detect the orientation of the device and even sense if a device is falling.

The X axis runs horizontally across the device.  The Y axis runs vertically across the device.  The Z axis runs immediately through the device, from front to back.  Here’s an image to help illustrate, using a Windows Phone as the example (courtesy of http://www.andybeaulieu.com/):

25-Accelerometer

In simpler terms, we’re measuring the g-forces applied to those three axes.  Because of this, when we lay a Windows 8 tablet flat on a table, we get a Z axis value of –1, because there is one “g” (one unit of gravity) exerting itself on the negative size of the Z axis.  In the same way, if we propped our device up (similar to the phone in the photo) so that the bottom of the device is sitting on the table, we would get a Y axis value of –1.

Working with the accelerometer is very similar to working with the other sensors. Just a few simple steps and we’re getting data.

  • Initialize the Sensor.
  • If it’s available,
    • create a readingchanged event handler.
    • create a shaken event handler
  • In the event handlers, grab the data from the sensor and write it to the screen.

Here’s my the entirety of my code and it looks scary similar to that of the other sensors.

var _x, _y, _z, _wasShaken;

    function onReadingChanged(e) {
        _x.innerText = e.reading.accelerationX;
        _y.innerText = e.reading.accelerationY;
        _z.innerText = e.reading.accelerationZ;
    }

    function onShaken(e) {
        _wasShaken.innerText = e.timestamp;
    }

    function getDomElements() {
        _x = document.querySelector("#x");
        _y = document.querySelector("#y");
        _z = document.querySelector("#z");
        _wasShaken = document.querySelector("#shaken");
    }

    function startAccelerometer() {
        var acc = Windows.Devices.Sensors.Accelerometer.getDefault()

        if (acc) {
            var minimumReportInterval = acc.minimumReportInterval;
            var reportInterval = minimumReportInterval > 16 ? minimumReportInterval : 25;
            acc.reportInterval = reportInterval;

            acc.addEventListener("readingchanged", onReadingChanged);
            acc.addEventListener("shaken", onShaken)
        }
    }

    app.onloaded = function () {
        getDomElements();
        startAccelerometer();
    }

Again, no real surprises here. We get to our data in the same basic was as we did with the other sensors.  Now the accelerometer sensor did introduce a new event called shaken. This event fires when a user shakes their machine In writing this article I was using the original build tablet for testing. I shook the machine but sadly couldn’t seem to get the event to fire. Just when I started to think I didn’t have a sensor which supported that event, I’d tossed down the machine down onto the couch and all of the sudden it fired. Turns out, I just wasn’t holding it right.

Summary

Today we briefly looked at getting data from our accelerometer. Working with each of the different sensors is all very similar.  Ultimately, how you use this data is where your real creativity comes in and I’m looking forward to hearing how you’ll use it in your app.

If you’d like to download my working sample that uses the code from this article, click the icon below:

 downloadHTML

Tomorrow, we’re going to look at the Gyrometer.  See you then!

downloadTheTools

Posted in 31 Days, Windows 8 | Tagged , | 1 Comment

31 Days of Windows 8 | Day #24: Light Sensor

This article is Day #24 in a series called 31 Days of Windows 8.  Each of the articles in this series will be published for both HTML5/JS and XAML/C#. You can find additional resources, downloads, and source code on our website.

advertisementsample

Today, we are taking a look another one of the sensors we might find in a Windows 8 device: the Light Sensor.  With the Light Sensor, we can determine the brightness of the light around the user’s machine, and help to accommodate things like contrast, brightness, and other values that would make our app easier to read in high and low light.

I let Jeff put together yet another horribly produced video to show you how a light sensor works, and what kinds of values we can expect. To make this application work, we’re going to follow a very similar pattern to the one we used yesterday for the Compass sensor.

  • Initialize the Light Sensor.
  • If it’s available, create a ReadingChangedevent handler.
  • In the event handler, grab the data from the sensor and write it to the screen.

Here’s my the entirety of my code and it looks scary similar to that of the compass.

var _light;

function onReadingChanged(e) {
    _light.innerText = e.reading.illuminanceInLux.toFixed(2);
}

function startLightSensor() {
    var lightSensor = Windows.Devices.Sensors.LightSensor.getDefault();

    if (lightSensor) {
        var minimumReportInterval = lightSensor.minimumReportInterval;
        var reportInterval = minimumReportInterval > 16 ? minimumReportInterval : 16;
        lightSensor.reportInterval = reportInterval;

        lightSensor.addEventListener("readingchanged", onReadingChanged);
    }
}

function getDomElements() {
    _light = document.querySelector("#light");
}

app.onready = function () {
    getDomElements();
    startLightSensor();
}

There’s nothing surprising about getting this data, but I was surprised to see how diverse the values on different machines (that were sitting next to each other) could be.  For instance, my Qualcomm ARM device (the one featured in the video above) generally rated the room I’m currently sitting in around 59 lux.  My Samsung tablet, however, which is a Windows 8 Pro device, rates this room around 42 lux.  Finally, my Surface RT device says this place is about 115 lux.

This is likely due to the accuracy and quality of the light sensor in each device, but in general, they’re really not that far apart on the scale of lux values.  Here’s an example from the Wikipedia article on Lux.

24-XAML-LuxChart

As you can see, even 100 lux is still a pretty dim value.  Just flipping the lightswitch on in my office jumped my sensor values up closer to 175.  Using the chart above, however, you should be able to create “ranges” of values that behave differently depending on the brightness of the light available.

For example, if you recognize that the user is in a low-light environment, you might switch their display to show a dark background and white text, because that is easier to read in that kind of light.  In a bright room, you might want to switch to black text on a white background.

In either case, you now know how to recognize the data from the light sensor, and use it effectively in your app.

Summary

Today we talked about the Light Sensor, and how it can be used to alter a user’s interface to make it more readable.  Ultimately, there are dozens of creative ways to leverage the lux data in your applications, and I’m looking forward to hearing how you’ll use it in your app.

If you’d like to download my working sample that uses the code from this article, click the icon below:

downloadHTML

Tomorrow, we’re going to get involved with a more robust sensor, the Accelerometer.  We can use this data to determine the rotation of the user’s device.  See you then!

downloadTheTools

Posted in 31 Days, Windows 8 | Tagged , | Leave a comment

31 Days of Windows 8 | Day #23: The Compass

This article is Day #23 in a series called 31 Days of Windows 8.  Each of the articles in this series will be published for both HTML5/JS and XAML/C#. You can find additional resources, downloads, and source code on our website.Compass

Today, we’re going to talk about the compass. While we’ve talked about one sensor in the past (Orientation Sensor), this is the first article of many to come focused just on the supported sensors. As a web developer this is really something completely new for me as it’s really outside the bounds of what we might typically do. Having said our web world is changing ever so fast.

Now if you’ve ever done any phone development then this isn’t anything new as our phones ( especially the ones on the shelf today ) have had these capabilities. If you have done any Windows Phone development previously, you might have read Jeff’s article on the Windows Phone compass, which provides magnetic and true north headings, as well as X, Y, and Z rotation data.

In Windows 8 this is different and provides significantly less data from the compass sensor.  In fact, we only get the values related to our heading, with no consideration for rotation data.  In addition, you’re going to find that since we’re building apps for Windows 8, there’s going to be a wide variety of sensors we’ll encounter. Now having said that, we can get rotation from the orientation sensor which we’ve already talked about on day #2. I would also check out this quick start on retrieving the quaternion and rotation matrix if you’re interested more in rotation.

Ok, on with the show.

Writing Some Code to Access the Compass

The compass, like many of the sensors we will cover over over the next few days, the compass is actually very accessible and easy to use.  With a few lines of code, and one event handler, we can gather rich data from our user’s device very quickly.  Here’s is all the code I needed to to start getting real-time data from my simple compass app:

    var _trueNorth, _magNorth, _timestamp;

    function onReadingChanged(e) {
        var newReading = e.reading;
        _timestamp.innerText = newReading.timestamp;
        _magNorth.innerText = newReading.headingMagneticNorth.toFixed(2);
        
        if (newReading.headingTrueNorth != null) {
            _trueNorth.innerText = reading.headingTrueNorth.toFixed(2);
        }
    }

    function startCompass() {
        var compass = Windows.Devices.Sensors.Compass.getDefault();

        if (compass) {
            var minimumReportInterval = compass.minimumReportInterval;
            var reportInterval = minimumReportInterval > 16 ? minimumReportInterval : 16;
            compass.reportInterval = reportInterval;

            compass.addEventListener("readingchanged", onReadingChanged);
        }
    }

    function getDomElements() {
        _trueNorth = document.querySelector("#trueNorth");
        _magNorth = document.querySelector("#magNorth");
        _timestamp = document.querySelector("#timestamp");
    }

    app.onloaded = function () {
        getDomElements();
        startCompass();
    }

To explain the code above, in my startCompass() method, I try to initialize my Compass object, and if it’s not null ( meaning there is a compass sensor on the machine ), I create an event handler for each time that the reading of the compass changes.  (Unless the user’s device is sitting completely still, it’s likely you’ll consistently get new readings.)  In the onReadingChanged event handler, I then assign our three values, HeadingMagneticNorth, HeadingTrueNorth, and Timestamp to an element I declared in our markup.

That’s it.  As you probably saw, however, most of the sensors you’re going to encounter will not provide ( as mine didn’t either ) a HeadingTrueNorth value, so relying on the HeadingMagneticNorth is going to be a more reliable value for you.

Finally, both of the Heading values are measured in degrees relative to their associated heading.  This means that you’ll see a range of values from 0 to 360, with zero being the value headed directly north.

Summary

This was a quick but exhaustive look at the Compass in Windows 8.  We saw that you can easily access the Compass data by using an event handler, but that we receive a limited amount of data from this sensor, and your mileage will vary from device to device.

If you would like to download the sample app featured in this article, click the icon below:

downloadHTML

Tomorrow, we’re going to look at the light sensor, and how we can manipulate our application to take advantage of knowing if the user is sitting in a light or dark room.

downloadTheTools

Posted in 31 Days, Windows 8 | Tagged , | 2 Comments

31 Days of Windows 8 | Day #22: Play To

This article is Day #22 in a series called 31 Days of Windows 8.  Each of the articles in this series will be published for both HTML5/JS and XAML/C#. You can find additional resources, downloads, and source code on our website.logo

It’s day Day 22. We’ve crawled all around Windows 8 but today we get to talk about a feature that seems to lack any press; Play To. I said yesterday that today we would talk about how to send the pictures and videos to another machine and this is exactly what we’re going to do; with Play To.

Let’s set this up some. I am an unusual customer. I have many many computers, smartphones, internet connected TVs, XBOXs and so on. I’ve even been in the long process of home automation. Basically if it needs electricity, I probably want it. But I am also a family man, who takes a lot of pictures, videos and whatnot. When you have all this great tech why not use it to its fullest potential?

And then there is software. I love software. I love the fact that we can make something that solves the needs for us to do something else. I love that I can just sit down and create something simple like On Time and hopefully make a presenters life just a little bit easier.

The place that’s always fallen down for me was the integration between the two. If’ you’ve ever tried to dip your toe into the home automation space then you know exactly where I am coming from. It’s like someone threw up electronic parts in a room and left you a flat head screwdriver to try and get them all to work together.

Now Play To isn’t the savior, but it’s  a great start. It brings together a very important gap we’ve today, media sharing.  By media, I mean, images, audio, and video. Media today is a mess, from the makers, to the providers to just my own organization of my music and pictures. I can say we’re not going to fix that here but maybe we can send that mess around to your different devices AND applications.

This is the first article where we’re going to need multiple devices to effectively test this. Today I am just going to use two different machines, the one I am doing development on and the Samsung Build Tablet. That doesn’t mean there isn’t an array of hardware out there that you could use to test. Microsoft has a great little site that will list the different compatible devices.

Before we get into the coding, I want to make sure you have a way to test this functionality.  In Windows 8, open the Windows Media Player app.  (You know, the app that you haven’t opened on a Windows machine in 10 years?  Yeah, that one.)

22-XAML-WindowsMediaPlayer_thumb2

Select the “Allow remote control of my Player…” option.  You’ll be asked to confirm your choice, just to make sure this is actually what you want to do.

22-XAML-AllowRemoteControl2

Once you’ve confirmed this choice, your machine will be registered on your network as a device available for Play To content.  OK, let’s get to coding, so that we can see what this really means.

Send To

The easiest way to think about Play To is just as another device. If you remember back to how we interfaced with the printers in Devices Charm, this is more of the same. The first thing we need to do is create our Play To Manager.

var _playToMgr = Windows.Media.PlayTo.PlayToManager.getForCurrentView();

Once we have that, then we need to registered for the sourcerequested event. This is the magic sauce that registers your app with Windows telling it we have some content that we can send along.

_playToMgr.addEventListener("sourcerequested", sourceRequestHandler, false);

With our event registered we just need to implement that handler. This will get fired when the user activates the Devices Charm. When our event fires we have to tell it what element we want to send along.

function sourceRequestHandler(e) {
    if (e)
        e.sourceRequest.setSource(_audioElement.msPlayToSource);
}

Ironically, that’s it. Here is the majority of the JS file I wrote to demonstrate the send. Clearly happy path, error free scenarios.

var _audioElement,
        _playToMgr = Windows.Media.PlayTo.PlayToManager.getForCurrentView();

function sourceRequestHandler(e) {
    if (e)
        e.sourceRequest.setSource(_audioElement.msPlayToSource);
}

function getDomElements() {
    _audioElement = document.querySelector("#audioTag");
}

function wireEventHandlers() {
    _playToMgr.addEventListener("sourcerequested", sourceRequestHandler, false);
}

app.onloaded = function () {
    getDomElements();
    wireEventHandlers();
}

Let’s Play

My UX is simple, it’s one audio element wired to my podcast, Developer Smackdown.

image

When I select the Devices Charm you will now see my tablet shown below.

image

After selecting that. my tablet will start playing the audio.

WP_20121121_001

And, if that isn’t trippy enough. Hit pause on your Played To device. You will see the pause change on your source machine. So you have full fidelity controls between the two devices.

- play to tip -

If you switch networks, say you go to a McDonalds to work for a while, maybe even write an article. You have to go through that brief setup we did at the start of this article ( at least for Windows Media Player ).

Receiving Content

Ok, now for the other way around. I honestly don’t know what is more exciting, the fact that you can send stuff or receive stuff. Believe me, the app ideas are rolling.

Receiving content is for the most part just as easy. We can break up the steps into 5 different parts:

  • create the receiver
  • set some properties on the receiver
  • wire the event handlers for the receiver
  • wire the event handlers for the element ( in our case an audio control )
  • start

To create the receiver we just need an instance of of the PlayToReceiver.

var _receiver = new Windows.Media.PlayTo.PlayToReceiver();

Next we have some properties we can set. I think the properties are self explanatory.

_receiver.friendlyName = "31 Days Play To Receiver";
_receiver.supportsAudio = true;
_receiver.supportsVideo = false;
_receiver.supportsImage = false;

With the properties set the next step is the most tedious, creating all of the event handlers. These event handlers are the things that map the events from both sides and your code is basically just a pass through. For example. If a user hits pause on the destination device, you need to map pause from that element back to the receiver so you can actually pause your element. The same is true the other way. Pause on the source, we hit pause on the destination and so on.

_receiver.addEventListener("sourcechangerequested", receiver_SourceChangeRequested);
_receiver.addEventListener("pauserequested", receiver_PauseRequested);
_receiver.addEventListener("currenttimechangerequested", _receiver_CurrentTimeChangeRequested);
_receiver.addEventListener("mutechangerequested", receiver_MuteChangeRequested);
_receiver.addEventListener("playbackratechangerequested", _receiver_PlaybackRateChangeRequested);
_receiver.addEventListener("playrequested", receiver_PlayRequested);
_receiver.addEventListener("stoprequested", receiver_StopRequested);
_receiver.addEventListener("timeupdaterequested", receiver_TimeUpdateRequested);
_receiver.addEventListener("volumechangerequested", receiver_VolumeChangeRequested);

_audioReceive.addEventListener("durationchange", audioPlayer_DurationChange);
_audioReceive.addEventListener("ended", audioPlayer_Ended);
_audioReceive.addEventListener("error", audioPlayer_Error);
_audioReceive.addEventListener("loadedmetadata", audioPlayer_LoadedMetadata);
_audioReceive.addEventListener("pause", audioPlayer_Pause);
_audioReceive.addEventListener("playing", audioPlayer_Playing);
_audioReceive.addEventListener("ratechange", audioPlayer_RateChange);
_audioReceive.addEventListener("seeked", audioPlayer_Seeked);
_audioReceive.addEventListener("seeking", audioPlayer_Seeking);
_audioReceive.addEventListener("volumechange", audioPlayer_VolumeChange);

I’m going to spare you the detail of the functions, just go look at the sample code. It’s just mapping code, a line or two each.  Now we just need to hit start the receiver so we can broadcast on the network.

_receiver.startAsync().done(function () {
    // good place to think about locking the display on.
});

And just like that, you’re now streaming back and forth between devices on your network. Seriously cool stuff that I would encourage you to play around with.

Summary

I’m really excited about the potential that Play To has. It open a unique scenario for media between devices and applications. Now what we do with it, is a different story. I could go on, but why? You should just start playing with it.

If you would like to download the sample code that was discussed in this article, click the icon below:

downloadHTML

Tomorrow, it’s off to more devices.

downloadTheTools

Posted in 31 Days, Windows 8 | Tagged , , , , | 1 Comment