Getting Accelerometer Data in Javascript for your Gear 2 Apps [Sample Code]

DSC_0010

One more important way to overcome user-interaction challenges on wearable devices is to implement hands-free interaction via sensors. Today, we’ll be looking at code to obtain tilt information from the Gear 2 accelerometer sensor. Luckily, it is a straightforward and easy process.

How to Access Accelerometer data in Javascript

To do this, you simply add an event listener for the “devicemotion” event. Next you get the X , Y and Z tilt values ( between 0  – 9 ) for both the X ,Y and Z axis.

See Also : How to store data in your gear 2 apps

window.addEventListener('devicemotion', function(e) {
		ax = e.accelerationIncludingGravity.x;
		ay = -e.accelerationIncludingGravity.y;
		az = -e.accelerationIncludingGravity.z;
		document.getElementById("xaccel").innerHTML =  'X : ' +  ax;
		document.getElementById("yaccel").innerHTML = 'Y : ' + ay;
		document.getElementById("zaccel").innerHTML = 'Z : ' + az;

	});

As you tilt the device in each direction, the values increment (with very high precision and at a very fast refresh rate too ..) from 0 –  9 and you can use this as a form of input in your app, especially in your games! And thats it!

Update : You can also get Data on Rotation

rotx = e.rotationRate.alpha ;
roty = e.rotationRate.beta ;
rotz = e.rotationRate.gamma ;

 

Gimme that Code ..

I’v created a sample Tizen Wearable Project which you can import and modify right there on Github .

Testing the Code Without A Real Device.

The Gear 2 tizen emulator doesnt come with the ability to inject dummy accelerometer values (or that I know of currently) . There however is another way to emulate your accelerometer values. You can use the Chrome Browser, since the functions used fall within the html5 specification. You can use the following steps

– Open your html file in the chrome browser (outside of the sdk environment) . In this case, we will open index.html
– Press F12 (Ctrl + Shift + I) to reveal the Chrome developer tools panel .

panel
– Press the escape button (ESC) to reveal the emulation tab
– Select Emulation, and under screen set your width and height to 320 px. Also set the pixel ration to 1. This mirrors the gear 2 device screen quite closely.
– Still under emulation, click sensors and you should be presented with accelerometer options. To modify the values, you can rotate the the image displayed and appropriate accelerometer values are generated.

panel2

Your window.addEventListener(‘devicemotion’, function) listener should respond to these changes/generated accelerometer values .

A Simple Application of the Accelerometer

Checkout dansa .. a fun dance companion app that tracks your dance moves as you boogie down! You know you can dance, and Dansa can prove it! Turn on some music, turn on dansa, start dancing and earn points! Yes, dansa is PERFECT for your dance workout! Also enjoy the flashy animations that light up the screen as you earn those awesome dansa points.

 

About Vykthur

Mobile and Web App Developer and Researcher. Passionate about learning, teaching, and recently - writing.
This entry was posted in Tutorials, Wearables and tagged , , . Bookmark the permalink.
  • Rifat

    is there anyway to run this application using Gear2 emulator ?

    • Vykthur

      Hi ,

      Currently, there is no direct method that I know of. The emulator only provides flick gestures and pedometer emulation. However you can emulate accelerometer in your browser.
      I have updated the article above to reflect how you can do that.

      -V

  • Vu Anh Truong

    Is there anyway to detect north south west east???

  • Bin Liu

    HI, thanks for the useful post.

    Is it possible to get the Gyroscope data?

    • Vykthur

      I think you can get gyroscope information by looking at the rotation along each axis .. e.g

      rotx = e.rotationRate.alpha ;

      roty = e.rotationRate.beta ;

      rotz = e.rotationRate.gamma ;

      The article and code have been updated.

      -V.

      • Bin Liu

        This is good enough! Thank you sir!

  • Bon Jae Koo

    Hi, I am running a project which is related to these sensors(acceler, gyro).
    However, I realize the sampling rate is really low on gyrosensor. is there any way to improve the rate??
    thanks 🙂

    • Vykthur

      Hi Jae,
      I think I understand your comment. From my own tests, it appears the accelerometer value gets updated several times a second very fast , while the rotation (gyro) values are slower. I am not sure why this is . Will update this discussion if I find out anything new. Also feel free to post if you find out anything new also.

      -V.

      • Bon Jae Koo

        Hi V,
        I am a member of Samsung Software Membership. So I got the opportunity to meet a worker in software center a few days ago. As he mentioned, the gear 2.0 doesn’t provide API to control sampling rate. In other words, the rate is fixed as 1 Hz. Therefore Samsung is going to provide the improved API in gear 3.0.
        Thanks

        -koo

        • Vykthur

          Thanks alot koo …
          Thanks for sharing this update.

          -V.

  • hong

    Hi, I would like to use you app to collect some accelerometer data. but I don’t have a device to test right now. I am wondering whether it is possible to read and log accelerometer continously on the background while the watch’s screen is locked? thanks

    • Vykthur

      Yes, this should be possible …
      You will just need to ensure your app runs in the background … and you save this data in a manner that is persistent across app launch ( a database, or localstorage)

      -V.

      • todicus

        I notice with the listener attached to the window, like this:

        window.addEventListener(‘devicemotion’, function(e) {

        then the accelerometer data stops working when the screen is dark. I wonder if we could attach the event to another object to keep it working even when the screen is dark? Although the W3C specification says that devicemotion events must be attached to a window object: http://www.w3.org/TR/2011/WD-orientation-event-20111201/#devicemotion

        • Vykthur

          Hi tod,
          Maybe you could keep the screen on while your app work?
          You can prevent the screen from going dark using the power mgt api.
          tizen.power.request(“SCREEN”, “SCREEN_NORMAL”);

          a little more on that here ..
          http://denvycom.com/blog/gear-2-developer-tips/

          -V.

          • todicus

            Thanks Vykthur, the devicemotion events keep firing if the power.request keeps the screen on. But I’d like to record for a long time, and the screen uses a lot of power! Seems like this must be possible, as the built-in Sleep app can sense motion while in blocking-mode, which keeps the screen from turning on for notifications / wrist up events / etc.

          • Vykthur

            Hi Tod,

            You are right … keeping screen on for a long period isnt that good for ur usecase. Can you try enabling background activity in your config.xml ? Try that an see if accel data stops when screen goes dark …

          • todicus

            I should have mentioned that I had enabled background-support. This keeps the HRM working (sort of, sometimes it drops out, but maybe that’s just due to motion of the wearer making the HRM reading too noisy), but does not help the devicemotion event. I asked the samsung support team about this, maybe they have another magic incantation to solve this problem!

          • seyma

            Hi Tod,

            I’m dealing with the very similar problem now. Could you be able to solve it during this time? If so, i will be very appreciated if you can share it.

          • todicus

            Hi Seyma,

            What are you trying to do? I never found a way to keep the accelerometer working while the screen was off. I found the HRM so inaccurate that I stopped working on the project. The SDK has gone through a few revisions since then, and maybe is more flexible now?

  • todicus

    Great blog! Most helpful place on the internet for Gear coding, I think! Have you tried accessing heart rate data since the new version of the SDK came out Sept 3rd (https://developer.tizen.org/downloads/sdk/release-notes/tizen-sdk-wearable-1.0.0b3)? The change log says “The “HRM” MotionType has been added”, but I still get privilege violations even though I added the healthinfo privilege to my config.xml.

    • Vykthur

      Hi,

      It should run smoothly. However, I looked through the new docs … and theres a line at the bottom ..

      To guarantee that the Heart Rate Monitor application runs on a device with heart rate monitor, declare the following feature requirements in the config file:

      http://developer.samsung.com/tizen/feature/heart_rate_monitor

      Try it and let me know if it fixes your issue ?

      V.

      • todicus

        Thank for the reply Vykthur! I tried to go to that link, but it resolves to:

        http://developer.samsung.com/home.do

        I wonder if Samsung has some kind of country-specific feature list? Would you mind copying the feature requirements to a response here?

        Thank you!

        • Vykthur

          What I meant is that you add that line (url) to your config.xml file .
          You can find more explanation in the IDE help content

          Help > Help Content

          Tizen Wearable Web App Programming > API References > Device API Reference > System

          -V.

          • todicus

            Oh haha, gotcha. I’ll try it. I read somewhere you need the healthinfo privilege, which I have already added to config.xml. I didn’t see any reference to heart_rate_monitor, but I think that is because the reference documentation gets mangled if you upgrade Tizen Wearable IDE to 1.0.0b3, rather than uninstall and start from scratch.

            Thanks for your help!

          • Vykthur

            🙂 … You are actually right, the healthinfo priviledge is supposed to take care of violation issues. I havent had time to do some test coding recently, but will update this post/comment when I do. Feel free to also share any insights you get on resolving the issue.

            -V.

          • Vykthur

            Hey todd,

            Did you manage to get the HRM working ? I have made some time out recently to test the code in the documentation and it still throws the privilege error.

            -V

          • todicus

            Nope, still getting the same privilege error. I’ve gone back and forth with Samsung developer support quite a bit. I sent them my log files generated when the app launches and throws the error; they are trying to figure it out (I hope, haven’t heard back in 4 days!). I will definitely let you know if I ever figure it out!

          • Vykthur

            Thanks alot! I’ll also let you know if I fix iit.
            -V

          • todicus

            Okay, I heard back from Samsung. For HRM you need two privileges:

            “http://developer.samsung.com/privilege/medicalinfo”

            “http://developer.samsung.com/privilege/healthinfo”

            I can get HRM data in my app now!

          • Vykthur

            Amazing …. there is no mention of medical info anywhere in the documentation. Thanks alot for sharing.
            I guess many got this info before now, but never bothered to share.

            Thanks for sharing! I’ll try it out asap.

            -V.

  • todicus

    Does rotationRate still work in the new SDK release (1.0.0b3)? I’m getting nulls for e.rotationRate.alpha, e.rotationRate.beta, e.rotationRate.gamma.

    Checking for capabilities indicates the gyro is accessible:

    deviceCapabilities = tizen.systeminfo.getCapabilities();
    console.log(deviceCapabilities.gyroscope); // returns “true”

  • PL_itto

    I got data from “devicemotion” on my Gear 2 neo, and the problems is :
    + Values of Accelerometer has fast refresh rate. But Values of Gyroscope hast very low refresh rate.
    + How to improve Gyroscope refresh rate ?
    Sorry for my bad English.

  • Draphes noraA

    I’m able to see the accelerometer data on my gear 2, but is there a way I can transmit the data to my computer for real time analysis ?