PythonIDE Docs
中文
简体中文

motion

设备运动、陀螺仪、磁力计和气压计。

设备运动传感器:加速度、重力、陀螺仪、磁力计、姿态与气压高度。

边界:传感器耗电;start_* 后必须 stop_*。读取放在按钮回调或 Timer 轮询,不要在 body() 里启动采集。模拟器数据有限,真机测试更可靠;读取可能返回 None,需判空。

#模块概览

说明
导入import motion
适合做什么运动仪表盘、倾斜检测、简单姿态反馈、气压变化
调用时机start_updates() 后轮询 get_*();停止时 stop_updates()
推荐顺序is_available()start_* → 采样 → stop_*
刷新频率UI 展示 0.2–1 秒一次即可,不必 60Hz 重建界面

#快速开始

下面脚本启动综合运动更新并读取数据:

python
import time
import motion

if not motion.is_available():
    print("当前设备不支持运动数据")
else:
    motion.start_updates(interval=1 / 30)
    try:
        time.sleep(0.2)
        print("加速度:", motion.get_acceleration())
        print("重力:", motion.get_gravity())
        print("旋转:", motion.get_rotation_rate())
        print("姿态:", motion.get_attitude())
    finally:
        motion.stop_updates()

单独使用气压计:

python
import motion

motion.start_altimeter()
try:
    print(motion.get_altitude())  # {pressure, relative_altitude}
finally:
    motion.stop_altimeter()

#AppUI 示例

开始/停止放在按钮回调;用 Timer 轮询采样,停止时关掉定时器。

python
import appui
import motion

state = appui.State(
    accel="—",
    attitude="—",
    status="点击开始采集",
)


def sample_motion():
    acc = motion.get_acceleration()
    att = motion.get_attitude()
    if acc:
        state.accel = f"x={acc['x']:.2f} y={acc['y']:.2f} z={acc['z']:.2f}"
    if att:
        state.attitude = f"roll={att['roll']:.2f} pitch={att['pitch']:.2f}"


poll_timer = appui.Timer(interval=0.5, repeats=True, action=sample_motion)


def start_sampling():
    if not motion.is_available():
        state.status = "设备不支持运动数据"
        return
    motion.start_updates(interval=1 / 30)
    poll_timer.start()
    state.status = "采集中…"


def stop_sampling():
    poll_timer.stop()
    motion.stop_updates()
    state.status = "已停止"


def body():
    return appui.NavigationStack(
        appui.Form([
            appui.Section("采样", [
                appui.Button("开始", action=start_sampling)
                .button_style("bordered_prominent"),
                appui.Button("停止", action=stop_sampling),
            ]),
            appui.Section("数据", [
                appui.LabeledContent("加速度", value=state.accel),
                appui.LabeledContent("姿态", value=state.attitude),
                appui.Text(state.status).foreground_color("secondaryLabel"),
            ], footer="真机测试;停止时务必调用 stop_updates。"),
        ]).navigation_title("运动传感器")
    )


appui.run(body, state=state)

#API 参考

#速查

API作用
is_available()是否支持运动数据
start_updates / stop_updates综合 device motion
start_accelerometer / stop_accelerometer仅加速度计
start_gyroscope / stop_gyroscope仅陀螺仪
start_magnetometer / stop_magnetometer仅磁力计
start_altimeter / stop_altimeter气压高度计
get_acceleration()读取最新采样

#启动与停止

start_updates(interval=0) — 综合采集(加速度 + 陀螺仪 + 姿态等)。interval 为秒,1/30 ≈ 30Hz;0 使用默认约 60Hz。

python
motion.start_updates(interval=1 / 10)
# … 读取 …
motion.stop_updates()

各传感器可单独启停:start_accelerometerstart_gyroscopestart_magnetometerstart_altimeter

#读取

函数返回
get_acceleration(){x, y, z}None
get_gravity(){x, y, z}None
get_rotation_rate(){x, y, z}None
get_magnetic_field(){x, y, z}None
get_attitude(){roll, pitch, yaw}None
get_altitude(){pressure, relative_altitude}None

未启动对应 start_* 或硬件无数据时返回 None


#常见错误

错误写法后果修正
startstop持续耗电try/finally 或按钮停止
body()start_updates刷新时重复启动放进按钮回调
不判断 None解包崩溃if data:
高频重建大界面卡顿Timer 0.5s+ 或 Aurora 快路径
模拟器当真机数据全零或不可用真机验证

#相关文档

文档用途
haptics运动反馈震动
health步数等健康数据
device设备信息与电量
原生能力入口MiniApp 场景配方

#预期效果

运行示例后,界面应出现文档描述的目标结果;若与预期不符,先看「失败路径」并按返回值或日志排查。