OpenHarmony开发者论坛
标题:
如何读取运动传感器比如加速度传感器
[打印本页]
作者:
润开鸿_坚果
时间:
2024-6-6 21:26
标题:
如何读取运动传感器比如加速度传感器
[md]## 如何读取运动传感器比如加速度传感器
**第一步声明权限**
```
{
"name": "ohos.permission.ACCELEROMETER"
},
```
**第二步导入sensor (传感器)模块:**
```
import { sensor } from '@kit.SensorServiceKit';
```
**第三步设置加速度传感器数据回调监听:**
```
try {
sensor.on(sensor.SensorId.ACCELEROMETER, (data) => {
console.info('X-coordinate component: ' + data.x);
console.info('Y-coordinate component: ' + data.y);
console.info('Z-coordinate component: ' + data.z);
}, { interval: 10000000 });
} catch (err) {
console.error('On fail, errCode: ' + err.code + ' ,msg: ' + err.message);
}
```
## 完整代码
```
import { sensor } from '@kit.SensorServiceKit';
@Entry
@Component
struct SensorPage {
@State message: string = '加速度';
build() {
Column() {
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold).onClick(() => {
try {
sensor.on(sensor.SensorId.ACCELEROMETER, (data) => {
this.message = JSON.stringify(data)
console.info('X-coordinate component: ' + data.x);
console.info('Y-coordinate component: ' + data.y);
console.info('Z-coordinate component: ' + data.z);
}, { interval: 10000000 });
} catch (err) {
console.error('On fail, errCode: ' + err.code + ' ,msg: ' + err.message);
}
})
}
.height('100%').justifyContent(FlexAlign.Center)
.width('100%')
}
}
```
**完毕。**
[/md]
欢迎光临 OpenHarmony开发者论坛 (https://forums.openharmony.cn/)
Powered by Discuz! X3.5