LoginSignup
10
14

More than 5 years have passed since last update.

ブラウザで歩数計【Javascript】

Posted at

ブラウザの機能で歩数計を作ってみました。

  • 加速度センサーの値だけで歩数を計測
  • 重力加速度ベクトルの大きさの変動を使用
// 重力加速度のしきい値
var GRAVITY_MIN = 9.8;
var GRAVITY_MAX = 12.00;
// 歩数
var _step = 0;
// 現在歩いているかどうか
var _isStep = false;

function initialize() {
    // デバイスの加速度センサーの情報を取得します
    window.addEventListener('devicemotion', onDeviceMotion);
}

function onDeviceMotion(e) {
    e.preventDefault();
    // 重力加速度を取得
    var ag = e.accelerationIncludingGravity;
    // 重力加速度ベクトルの大きさを取得
    var acc = Math.sqrt(ag.x*ag.x + ag.y*ag.y + ag.z*ag.z);
    // 
    if (_isStep) {
        // 歩行中にしきい値よりも低ければ一歩とみなす
        if (acc < GRAVITY_MIN) {
            _step++;
            _isStep = false;
        }
    } else {
        // しきい値よりも大きければ歩いているとみなす
        if (acc > GRAVITY_MAX) {
            _isStep = true;
        }
    }
    console.log(_step + "");
}
10
14
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
14