Skip to main content
Use this API to listen for accelerometer data changes. The callback provides x, y, and z axis acceleration values.

Parameters

PropertyTypeRequiredDescription
callbackFunctionYesCallback function when accelerometer data changes

Callback Parameters

PropertyTypeDescription
xNumberAcceleration along X axis
yNumberAcceleration along Y axis
zNumberAcceleration along Z axis

Code Example

Basic Usage

my.onAccelerometerChange((res) => {
  console.log('X:', res.x);
  console.log('Y:', res.y);
  console.log('Z:', res.z);
});

Motion Detection

Page({
  data: {
    lastShake: 0
  },

  onLoad() {
    my.onAccelerometerChange((res) => {
      const acceleration = Math.sqrt(
        res.x * res.x + res.y * res.y + res.z * res.z
      );

      if (acceleration > 1.5) {
        const now = Date.now();
        if (now - this.data.lastShake > 1000) {
          this.setData({ lastShake: now });
          this.handleShake();
        }
      }
    });
  },

  handleShake() {
    my.vibrate();
    console.log('Device shaken!');
  }
});

Tilt Detection for Games

Page({
  onLoad() {
    my.onAccelerometerChange((res) => {
      // Use x/y for tilt-based controls
      this.setData({
        tiltX: res.x * 90, // Convert to degrees
        tiltY: res.y * 90
      });
    });
  }
});
Call my.startAccelerometer before using this API to begin receiving accelerometer data.

my.offAccelerometerChange

Stop listening for changes

my.startAccelerometer

Start accelerometer