Detecting device shake in JavaScript

In the 7th Stupid Hackathon in Thailand, during pitching, we wanted the audience to vote for their favorite projects by shaking their phone. For that, a shake detection algorithm was needed.

The voting web application was built by @boomchanotai, while I just contributed the shake detection algorithm. You can read my write-up about the experience and see the video demo of the application used in the hackathon here (Thai language).

For the demo to work, you need to open this page on a mobile device and allow the page to access the device motion sensor.


x: 0.00, y: 0.00, z: 0.00

Shake counter
0
Median shake speed for the last 10 shakes: - shakes/sec

The shake detection algorithm

Three-panel diagram explaining a device shake detection algorithm on a black background. First, a shake is started when the acceleration exceeds 30 m/s^2. We remember acceleration vector as the activation vector a0. Formula: ||a|| > 30. First way to stopping a shake: A shake is stopped when the acceleration goes under 20 m/s^2. Formula: ||a|| < 20. Second way to stop a shake: A shake is also stopped when the angle between the latest acceleration and the activation vector exceeds ~72° (cos^-1(0.3)). Formula: (a · a0) / (||a|| ||a0||) < 0.3.