1# Using Motion and Orientation Sensors 2 3## Overview 4 5The motion and orientation sensors, such as an accelerometer and a gyroscope, can monitor the motion status and orientation change (such as rotation and tilt) of the device. 6Through the W3C standards-compliant API, the **Web** component can access the sensor data to implement richer user interaction features. For example, in a web application, you can use an accelerometer to identify the motion mode and instruct the user to exercise, and use a gyroscope to capture the tilt and rotation of the device in the hand of the player, implementing game experience without button control. 7 8To access the motion and orientation sensors, invoke the following W3C standards-compliant APIs in JavaScript: 9 10| API | Name | Description | 11| ------------------------- | ------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------- | 12| Accelerometer | Accelerometer | Obtains acceleration data in the X, Y, and Z axes. | 13| Gyroscope | Gyroscope | Obtains angular velocity data in the X, Y, and Z axes. | 14| AbsoluteOrientationSensor | Absolute orientation | Obtains the quaternion including the X, Y, Z, and W components that indicates the absolute orientation of the device. | 15| RelativeOrientationSensor | Relative orientation | Obtains the quaternion including the X, Y, Z, and W components that indicates the relative orientation of the device. | 16| DeviceMotionEvent | Device motion event| Listens for the device motion events to obtain the acceleration data of the device in the X, Y, and Z axes, acceleration data that contains gravity in the X, Y, and Z axes, and rotation rate data of the device in the alpha, beta, and gamma axes.| 17| DeviceOrientationEvent | Device orientation event| Listens for the device orientation events to obtain the angles of the device around the X, Y, and Z axes. | 18 19## Required Permission 20 21To use the preceding APIs, you need to declare the corresponding sensor permissions in the **module.json5** file. For details, see [Declaring Permissions](../security/AccessToken/declare-permissions.md). 22 23``` 24 "requestPermissions":[ 25 { 26 "name": "ohos.permission.ACCELEROMETER" // Accelerometer permission 27 }, 28 { 29 "name": "ohos.permission.GYROSCOPE" // Gyroscope permission 30 } 31 ] 32``` 33 34When the **Web** component is connected to a motion or orientation sensor, configure [onPermissionRequest](../reference/apis-arkweb/ts-basic-components-web.md#onpermissionrequest9) to receive permission request notifications. 35 36## How to Develop 37 381. In the application code, configure [onPermissionRequest](../reference/apis-arkweb/ts-basic-components-web.md#onpermissionrequest9) for the **Web** component and use the [getAccessibleResource](../reference/apis-arkweb/ts-basic-components-web.md#getaccessibleresource9) API of [PermissionRequest](../reference/apis-arkweb/ts-basic-components-web.md#permissionrequest9) to obtain the resource type of the request permission. When the resource type is **TYPE_SENSOR**, the sensor is authorized. 39 40 ```ts 41 import { webview } from '@kit.ArkWeb'; 42 import { abilityAccessCtrl, PermissionRequestResult } from '@kit.AbilityKit'; 43 import { BusinessError } from '@kit.BasicServicesKit'; 44 45 @Entry 46 @Component 47 struct WebComponent { 48 controller: webview.WebviewController = new webview.WebviewController() 49 aboutToAppear() { 50 // Enable web frontend page debugging. 51 webview.WebviewController.setWebDebuggingAccess(true); 52 // Create an **AtManager** instance, which is used for application access control. 53 let atManager = abilityAccessCtrl.createAtManager(); 54 try { 55 atManager.requestPermissionsFromUser(getContext(this), ['ohos.permission.ACCELEROMETER', 'ohos.permission.GYROSCOPE'] 56 , (err: BusinessError, data: PermissionRequestResult) => { 57 console.info('data:' + JSON.stringify(data)); 58 console.info('data permissions:' + data.permissions); 59 console.info('data authResults:' + data.authResults); 60 }) 61 } catch (error) { 62 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 63 } 64 } 65 66 build() { 67 Column() { 68 Web({ src: $rawfile('index.html'), controller: this.controller }) 69 .onPermissionRequest((event) => { 70 if (event) { 71 AlertDialog.show({ 72 title: 'title', 73 message: 'text', 74 primaryButton: { 75 value: 'deny', 76 action: () => { 77 event.request.deny(); 78 } 79 }, 80 secondaryButton: { 81 value: 'onConfirm', 82 action: () => { 83 event.request.grant(event.request.getAccessibleResource()); 84 } 85 }, 86 autoCancel: false, 87 cancel: () => { 88 event.request.deny(); 89 } 90 }) 91 } 92 }) 93 } 94 } 95 } 96 ``` 97 982. In the frontend page code, use JavaScript to call the W3C standards-compliant API related to the sensor. 99 100 ```html 101 <!DOCTYPE HTML> 102 <html> 103 <head> 104 <meta charset="utf-8" /> 105 <meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no" /> 106 <meta name="misapplication-tap-highlight" content="no" /> 107 <meta name="HandheldFriendly" content="true" /> 108 <meta name="MobileOptimized" content="320" /> 109 <title>Motion and direction sensor</title> 110 <meta charset="UTF-8"> 111 <style> 112 body { 113 font-family: Arial, sans-serif; 114 } 115 </style> 116 <script type="text/javascript"> 117 // Access the accelerometer of the device and obtain its data. 118 function getAccelerometer() { 119 var acc = new Accelerometer({frequency: 60}); 120 acc.addEventListener('activate', () => console.log('Ready to measure.')); 121 acc.addEventListener('error', error => console.log('Error type: ' + error.type + ', error: ' + error.error )); 122 acc.addEventListener('reading', () => { 123 console.log(`Accelerometer ${acc.timestamp}, ${acc.x}, ${acc.y}, ${acc.z}.`); 124 }); 125 acc.start(); 126 } 127 128 // Access the gyroscope of the device and obtain its data. 129 function getGyroscope() { 130 var gyr = new Gyroscope({frequency: 60}); 131 gyr.addEventListener('activate', () => console.log('Ready to measure.')); 132 gyr.addEventListener('error', error => console.log('Error type: ' + error.type + ', error: ' + error.error )); 133 gyr.addEventListener('reading', () => { 134 console.log(`Gyroscope ${gyr.timestamp}, ${gyr.x}, ${gyr.y}, ${gyr.z}.`); 135 }); 136 gyr.start(); 137 } 138 139 // Access the orientation sensor of the device and obtain its data. 140 function getAbsoluteOrientationSensor() { 141 var aos = new AbsoluteOrientationSensor({frequency: 60}); 142 aos.addEventListener('activate', () => console.log('Ready to measure.')); 143 aos.addEventListener('error', error => console.log('Error type: ' + error.type + ', error: ' + error.error )); 144 aos.addEventListener('reading', () => { 145 console.log(`AbsoluteOrientationSensor data: ${aos.timestamp}, ${aos.quaternion}`); 146 }); 147 aos.start(); 148 } 149 150 // Listen for the motion events of the device and execute the corresponding processing logic. 151 function listenDeviceMotionEvent() { 152 removeDeviceMotionEvent(); 153 if ('DeviceMotionEvent' in window) { 154 window.addEventListener('devicemotion', handleMotionEvent, false); 155 } else { 156 console.log ("DeviceMotionEvent is not supported."); 157 } 158 } 159 160 // Remove the device motion event listener. 161 function removeDeviceMotionEvent() { 162 if ('DeviceMotionEvent' in window) { 163 window.removeEventListener('devicemotion', handleMotionEvent, false); 164 } else { 165 console.log ("DeviceOrientationEvent is not supported."); 166 } 167 } 168 169 // Handle the motion event. 170 function handleMotionEvent(event) { 171 const x = event.accelerationIncludingGravity.x; 172 const y = event.accelerationIncludingGravity.y; 173 const z = event.accelerationIncludingGravity.z; 174 console.log(`DeviceMotionEvent data: ${event.timeStamp}, ${x}, ${y}, ${z}`); 175 } 176 177 // Listen for the device orientation events and execute the corresponding processing logic. 178 function listenDeviceOrientationEvent() { 179 removeDeviceOrientationEvent(); 180 if ('DeviceOrientationEvent' in window) { 181 window.addEventListener('deviceorientation', handleOrientationEvent, false); 182 } else { 183 console.log ("DeviceOrientationEvent is not supported."); 184 } 185 } 186 187 // Remove the device orientation event listener. 188 function removeDeviceOrientationEvent() { 189 if ('DeviceOrientationEvent' in window) { 190 window.removeEventListener('deviceorientation', handleOrientationEvent, false); 191 } else { 192 console.log ("DeviceOrientationEvent is not supported."); 193 } 194 } 195 196 // Listen for the device orientation events and execute the corresponding processing logic. 197 function listenDeviceOrientationEvent2() { 198 removeDeviceOrientationEvent2(); 199 if ('DeviceOrientationEvent' in window) { 200 window.addEventListener('deviceorientationabsolute', handleOrientationEvent, false); 201 } else { 202 console.log ("DeviceOrientationEvent is not supported."); 203 } 204 } 205 206 // Remove the device orientation event listener. 207 function removeDeviceOrientationEvent2() { 208 if ('DeviceOrientationEvent' in window) { 209 window.removeEventListener('deviceorientationabsolute', handleOrientationEvent, false); 210 } else { 211 console.log ("DeviceOrientationEvent is not supported."); 212 } 213 } 214 215 // Handle the orientation event. 216 function handleOrientationEvent(event) { 217 console.log(`DeviceOrientationEvent data: ${event.timeStamp}, ${event.absolute}, ${event.alpha}, ${event.beta}, ${event.gamma}`); 218 } 219 </script> 220 </head> 221 <body> 222 <div id="dcontent" class="dcontent"> 223 <h3>Motion and orientation:</h3> 224 <ul class="dlist"> 225 <li><button type="button" onclick="getAccelerometer()">Accelerometer</button></li>; 226 <li><button type="button" onclick="getGyroscope()">Gyroscope</button></li> 227 <li><button type="button" onclick="getAbsoluteOrientationSensor()">Device (absolute) orientation</button></li>; 228 <li><button type="button" onclick="listenDeviceMotionEvent()">Device motion event</button></li>; 229 <li><button type="button" onclick="listenDeviceOrientationEvent()">Device orientation event</button></li>; 230 <li><button type="button" onclick="listenDeviceOrientationEvent2()">Device (absolute) orientation event</button></li>; 231 </ul> 232 </div> 233 </body> 234 </html> 235 ``` 236