Skip to main content
Use this API to start the accelerometer sensor. After calling this, you can use my.onAccelerometerChange to receive accelerometer data.

Parameters

PropertyTypeRequiredDescription
intervalStringNoData reporting interval: game (20ms), ui (60ms), normal (200ms). Default: normal
successFunctionNoCallback on success
failFunctionNoCallback on failure
completeFunctionNoCallback that always executes

Code Example

Basic Usage

my.startAccelerometer({
  success() {
    console.log('Accelerometer started');
  }
});

High Frequency for Games

my.startAccelerometer({
  interval: 'game', // 20ms updates
  success() {
    my.onAccelerometerChange((res) => {
      this.updatePlayerPosition(res.x, res.y);
    });
  }
});

Motion Tracking App

Page({
  data: {
    isTracking: false
  },

  startTracking() {
    my.startAccelerometer({
      interval: 'ui',
      success: () => {
        this.setData({ isTracking: true });
        my.onAccelerometerChange(this.recordMotion);
      },
      fail(err) {
        my.showToast({
          content: 'Failed to start accelerometer',
          type: 'fail'
        });
      }
    });
  },

  stopTracking() {
    my.offAccelerometerChange(this.recordMotion);
    this.setData({ isTracking: false });
  },

  recordMotion(res) {
    // Store motion data
    this.motionData.push({
      x: res.x,
      y: res.y,
      z: res.z,
      timestamp: Date.now()
    });
  }
});

Interval Options

ValueUpdate FrequencyUse Case
game~50 times/sec (20ms)Games requiring real-time response
ui~16 times/sec (60ms)UI animations and interactions
normal~5 times/sec (200ms)General motion detection
Higher frequency intervals consume more battery. Use normal or ui unless you specifically need game frequency for real-time applications.

my.onAccelerometerChange

Listen for accelerometer data

my.offAccelerometerChange

Stop listening