my.onGyroscopeChange

The my.onGyroscopeChange JSAPI is called by mini program developers to register listeners that monitor gyroscope data updates. The event trigger depends on the prior invocation of my.startGyroscope, with the callback frequency controlled by the interval parameter passed to my.startGyroscope.

Coordinate system

The device's coordinate system consists of the following three axes:

  • x-axis: Horizontal axis, running from left to right across the screen.
  • y-axis: Vertical axis, running from the bottom to the top of the screen.
  • z-axis: Perpendicular to the screen, pointing outward.

The following table illustrates how the device rotates around each axis:

X-axis rotation

Y-axis rotation

Z-axis rotation

Description

Tilt the device forward/backward

Tilt the device to the left/right

Rotate the device on a flat surface

Visual example

image

image

image

Parameters

Type

Required

Description

Function listener

Yes

A callback that monitors gyroscope data updates. When executed, it receives a res object containing updated gyroscope data.

res object

Parameter

Type

Required

Description

x

Number

Yes

The angular velocity (in rad/s) around the device's x-axis. For more information, refer to Coordinate system.

y

Number

Yes

The angular velocity (in rad/s) around the device's y-axis. For more information, refer to Coordinate system.

z

Number

Yes

The angular velocity (in rad/s) around the device's z-axis. For more information, refer to Coordinate system.

timestamp

Number

Yes

Timestamp (in nanoseconds) when the gyroscope data is recorded.

Sample code

copy
Page({
    // Define listeners to handle gyroscope data
    listener(res) {
        console.log("1" + JSON.stringify(res))
    },
    listener2(res) {
        console.log("2" + JSON.stringify(res));
    },
    // Start gyroscope monitoring and register listeners
    start() {
        my.startGyroscope({
            success: () => {
                my.onGyroscopeChange(this.listener);
                my.onGyroscopeChange(this.listener2);
            }
        });
    },
    // Stop gyroscope monitoring
    stop() {
        my.stopGyroscope();
    },
    // Remove a specific listener
    offSingle() {
        my.offGyroscopeChange(this.listener);
    },
    // Remove all registered listeners
    offAll() {
        my.offGyroscopeChange();  
    }
});