Working with Sensors
1. Using Accelerometer
| Property | Description | Values |
|---|---|---|
| acceleration.x | X-axis acceleration in m/s² | number |
| acceleration.y | Y-axis acceleration in m/s² | number |
| acceleration.z | Z-axis acceleration in m/s² | number |
| gravity.x | X-axis gravity in m/s² | number |
| gravity.y | Y-axis gravity in m/s² | number |
| gravity.z | Z-axis gravity in m/s² | number |
| userAcceleration.x | X-axis user acceleration in m/s² | number |
| userAcceleration.y | Y-axis user acceleration in m/s² | number |
| userAcceleration.z | Z-axis user acceleration in m/s² | number |
Example: Reading Accelerometer Data
import { Accelerometer } from 'expo-sensors';
const subscribe = Accelerometer.addListener((accelerometerData) => {
console.log("Acceleration: ", accelerometerData.acceleration);
});
// Unsubscribe when done
// subscribe.remove();
Note: Ensure that the device has accelerometer hardware and permissions are granted for sensor access.
2. Using Gyroscope
| Property | Description | Values |
|---|---|---|
| Gyroscope.isAvailable | Indicates if gyroscope sensor is available | true or false |
| Gyroscope.addListener | Registers a listener for gyroscope data | Function callback |
| Gyroscope.removeListeners | Removes all gyroscope listeners | None |
Example: Subscribe to Gyroscope Data
Gyroscope.addListener((gyroData) => {
console.log("Gyroscope Data:", gyroData);
});
Note: On some devices, gyroscope data might not be available or may require additional permissions.
3. Using Magnetometer
| Property | Description | Values |
|---|---|---|
| magnetometer | Provides access to the device's magnetometer sensor data | true or false |
Example: Reading Magnetometer Data
import { Magnetometer } from 'expo-sensors';
Magnetometer.addListener((magnetometerData) => {
console.log('Magnetic field (microtesla):', magnetometerData);
});
// Start listening
Magnetometer.setUpdateInterval(100); // Update every 100ms
Note: The magnetometer sensor provides data in microtesla (µT) units.
Warning: Not all devices support magnetometer sensors. Always check for sensor availability before using.
| Field | Description | Unit |
|---|---|---|
| x | X-axis magnetic field strength | µT |
| y | Y-axis magnetic field strength | µT |
| z | Z-axis magnetic field strength | µT |
4. Using Barometer
| Property | Description | Values |
|---|---|---|
| barometer.pressure | Current atmospheric pressure in hectopascals (hPa) | 1013.25 |
| barometer.altitude | Estimated altitude in meters based on pressure | 0 |
Example: Reading Barometer Data
import { Barometer } from 'expo-sensors';
Barometer.addListener((data) => {
console.log("Pressure:", data.pressure);
console.log("Altitude:", data.altitude);
});
Barometer.setUpdateInterval(1000); // Update every second
Note: Barometer sensor data is only available on devices with a pressure sensor.
Warning: Altitude calculation is approximate and may vary due to local weather conditions.
5. Using Pedometer
| Property | Description | Values |
|---|---|---|
| isAvailable | Indicates if the pedometer sensor is available on the device | true or false |
| stepCount | Current step count since the sensor started tracking | number |
| lastUpdate | Timestamp of the last update from the sensor | Date |
Example: Reading Pedometer Data
import * as Expo from 'expo-sensors';<br><br>// Check if pedometer is available<br>const isAvailable = await Expo.Pedometer.isAvailableAsync();<br><br>// Start watching pedometer data<br>const { steps, lastUpdate } = await Expo.Pedometer.watchPedometerDataAsync(<br> (data) => {<br> console.log('Steps:', data.steps);<br> console.log('Last Update:', data.lastUpdate);<br> }<br>);
Note: The pedometer sensor is only available on devices with a step counter (e.g., iOS devices with CoreMotion support).
6. Setting Update Interval
| Property | Values | Description |
|---|---|---|
| interval | 100 ms (default) |
Update interval in milliseconds |
| fastestInterval | 0 ms (default) |
Fastest update interval allowed |
Example: Configure Update Interval
import { Accelerometer } from 'expo-sensors';
Accelerometer.setUpdateInterval(200); // Update every 200ms
Note: Setting a faster interval may impact battery life and performance.
7. Adding Sensor Listeners
Example: Adding a Sensor Listener
import { Sensor } from 'expo-sensors';
const sensorListener = Sensor.watchSensor(
Sensor.TYPE_ACCELEROMETER,
(accelerometerData) => {
console.log("Acceleration X:", accelerometerData.x);
console.log("Acceleration Y:", accelerometerData.y);
console.log("Acceleration Z:", accelerometerData.z);
},
100 // Update interval in milliseconds
);
// To stop listening:
// Sensor.clearSensorListener(sensorListener);
| Parameter | Type | Description |
|---|---|---|
| sensorType | string |
Type of sensor to listen to (e.g., TYPE_ACCELEROMETER) |
| listener | function |
Callback function that receives sensor data |
| interval | number |
Update interval in milliseconds (optional) |
Note: The sensor listener will continue running until explicitly cleared using
Sensor.clearSensorListener().
8. Removing Listeners
Example: Removing a Sensor Listener
import { Sensor } from 'expo-sensors';
// Assume we have a listener set up
const sensorListener = Sensor.addListener(
Sensor.SensorType.ACCELEROMETER,
(data) => {
console.log('Accelerometer data:', data);
}
);
// Remove the listener
Sensor.removeListener(sensorListener);
| Method | Description | Parameters |
|---|---|---|
| Sensor.removeListener() | Removes a previously added sensor listener | listener - The listener to remove |
Note: Always remove listeners when they are no longer needed to prevent memory leaks and unnecessary updates.
9. Using Device Motion
| Property | Description | Values | Notes |
|---|---|---|---|
| acceleration | Current acceleration along the x, y, and z axes | { x: number, y: number, z: number } |
Unit is in m/s² |
| accelerationIncludingGravity | Acceleration including gravity | { x: number, y: number, z: number } |
Unit is in m/s² |
| rotationRate | Rotation rate around the x, y, and z axes | { alpha: number, beta: number, gamma: number } |
Unit is in deg/s |
| interval | Interval in milliseconds between updates | number |
Default is 100 ms |
Example: Using Device Motion
import { DeviceMotion } from 'expo-sensors';
const subscribe = DeviceMotion.addListener((motionData) => {
console.log('Acceleration:', motionData.acceleration);
console.log('Rotation Rate:', motionData.rotationRate);
});
// Start listening
DeviceMotion.setUpdateInterval(100);
// Stop listening
// DeviceMotion.removeSubscription(subscribe);
Note: On some devices,
accelerationIncludingGravity may not be available.
10. Checking Sensor Availability
| Sensor | Availability | Notes |
|---|---|---|
| Accelerometer | Available | Supported on all platforms |
| Gyroscope | Available | Supported on all platforms |
| Magnetometer | Available | Supported on all platforms |
| Barometer | Available | Only available on devices with barometer hardware |
| AmbientLight | Available | Supported on all platforms |
Example: Check Sensor Availability
import { Accelerometer, Gyroscope } from 'expo-sensors';
const isAccelerometerAvailable = await Accelerometer.isAvailableAsync();
const isGyroscopeAvailable = await Gyroscope.isAvailableAsync();
console.log('Accelerometer available:', isAccelerometerAvailable);
console.log('Gyroscope available:', isGyroscopeAvailable);
11. Handling Sensor Errors
Example: Error Handling with Sensor Data
import { Sensor } from 'expo-sensors';
try {
const data = await Sensor.getSensorDataAsync(Sensor.Type.ACCELEROMETER);
console.log('Sensor data:', data);
} catch (error) {
console.error('Sensor error:', error.message);
// Handle specific sensor errors
if (error.code === 'SENSOR_NOT_AVAILABLE') {
console.warn('Sensor not available on this device');
}
}
| Error Code | Description | Handling Recommendation |
|---|---|---|
| SENSOR_NOT_AVAILABLE | Sensor hardware not present or disabled | Check device capabilities and provide fallback UI |
| SENSOR_PERMISSION_DENIED | User denied sensor access permission | Prompt user to enable permissions in settings |
| SENSOR_DATA_ERROR | Malformed or corrupted sensor data | Retry read operation or log error for debugging |
Note: Always wrap sensor operations in try-catch blocks to gracefully handle runtime errors.
Warning: Some sensors may return
null or invalid data when the device is in low-power mode.
12. Using Light Sensor
| Property | Description | Values |
|---|---|---|
| ambientLight | Current ambient light level in lux | number |
Example: Reading Light Sensor Data
import { Sensor } from 'expo-sensors';
const subscribe = Sensor.watchSensor(
Sensor.TYPE_LIGHT,
(data) => {
console.log('Light level:', data.ambientLight);
}
);
// Unsubscribe when done
// subscribe.remove();
Note: The light sensor may not be available on all devices.
Warning: Continuous sensor reading can drain battery quickly.