Twitter: raymondcamden

Address: Lafayette, LA, USA

PhoneGap Sample - Shake to Roll

01-15-2013 10,913 views Mobile, JavaScript 3 Comments

Sorry for being so quiet lately. I've got three presentations this week and two brand new ones in two weeks. Mentally - it has been killing me. As with all things - it will pass. (And I think I'm building some good new presentations as well!) In the meantime, I thought I'd share a simple PhoneGap application I built for my four-hour lab in Ohio a few days back.

The idea behind the application was to demonstrate the Accelerometer API. This returns movement information along three different axes.

By itself, the API is easy enough to use. What I was having difficulty with was coming up with a practical example of it. I thought I'd create a simple application that mimicked rolling a die. I'd start off by selecting a random number between one and six. I'd display this on the screen like so.

(What you're seeing here is the Ripple emulator. I plan on talking about this in a few days.)

The code for picking and displaying a random number was trivial.

What was more difficult was figuring out how to respond to a shake. I mean, seriously, what is a shake, in code terms?

I did some Googling and discovered that most people simply tracked the X/Y/Z values and then compared them to historical values. I came up with this solution (which is based on what I saw so this isn't some brilliant discovery of mine).

I then used the Ripple emulator to test, and slowly tweaked the numbers until it "felt" right to me. You can see the result below.

For the full source code (there really isn't much to it), you can see the code in the GitHub repo for the presentation: DevelopingMobileAppsWithPhoneGap/tree/master/labs/6_accelerometer


These comments will soon be imported into Disqus. To add a comment, use Disqus above.
  • Rodney #
    Commented on 06-02-2013 at 1:51 AM
    Thanks - I do find that if I use a frequency of 200 then the shake event fires multiple times - e.g. 3 times on Ripple Emulator and on my Android S4. I set it to 500 and it seems to only fire once. Is it possible to adapt the code to only fire once and then not fire again if it is within a small period of time (after a few seconds it should keep listening)
  • Commented on 06-02-2013 at 8:24 AM
    It is kind of cheesy, but use a global var: paused

    When you begin the shake do:

    window.setTimeout(clearPause, 2000);

    clearPause will set paused to false. And before you do your shake. check if paused is true.
  • Rodney #
    Commented on 07-06-2013 at 2:25 AM
    Thanks, that worked. It is very sensitive!