by Isaías Chávez
A lightweight and modern accelerometer module for React Native, built with the New Architecture (TurboModules + Fabric). Provides real-time access to device acceleration data with high performance, low overhead, and a clean, predictable API.
npm install react-native-accelerometeror with Yarn:
yarn add react-native-accelerometerAfter installing the package, navigate to the iOS folder and install the pods:
cd ios && pod install && cd ..Or if you're in the root directory:
npx pod-installNo additional setup required. The package uses autolinking.
import React, { useEffect, useState } from 'react';
import { View, Text } from 'react-native';
import * as Accelerometer from 'react-native-accelerometer';
function App() {
const [data, setData] = useState({ x: 0, y: 0, z: 0 });
useEffect(() => {
// Check if accelerometer is available
const checkSensor = async () => {
const available = await Accelerometer.isAvailable();
console.log('Accelerometer available:', available);
};
checkSensor();
// Set update interval to 100ms
Accelerometer.setUpdateInterval(100);
// Start listening to accelerometer updates
Accelerometer.startUpdates();
// Subscribe to updates
const subscription = Accelerometer.addListener((accelerometerData) => {
setData(accelerometerData);
});
// Cleanup
return () => {
subscription.remove();
Accelerometer.stopUpdates();
};
}, []);
return (
<View>
<Text>X: {data.x.toFixed(4)}</Text>
<Text>Y: {data.y.toFixed(4)}</Text>
<Text>Z: {data.z.toFixed(4)}</Text>
</View>
);
}isAvailable(): Promise<boolean>Checks if the accelerometer sensor is available on the device.
Returns: Promise that resolves to true if available, false otherwise.
Example:
const available = await Accelerometer.isAvailable();
if (available) {
console.log('Accelerometer is ready to use');
}startUpdates(): voidStarts receiving accelerometer updates. Events will be emitted at the configured interval.
Example:
Accelerometer.startUpdates();stopUpdates(): voidStops receiving accelerometer updates and unregisters the sensor listener.
Example:
Accelerometer.stopUpdates();setUpdateInterval(intervalMs: number): voidSets the interval (in milliseconds) at which accelerometer updates are received.
Parameters:
intervalMs - Update interval in milliseconds (e.g., 100 for 10 updates per second)Example:
// Update every 50ms (20 times per second)
Accelerometer.setUpdateInterval(50);getCurrentAcceleration(): Promise<AccelerometerData>Gets the current acceleration data as a one-time reading.
Returns: Promise that resolves to an AccelerometerData object.
Example:
const data = await Accelerometer.getCurrentAcceleration();
console.log(`X: ${data.x}, Y: ${data.y}, Z: ${data.z}`);setGravityFilter(enabled: boolean): voidEnables or disables gravity filtering. When enabled, attempts to remove the gravity component from acceleration data.
Parameters:
enabled - true to enable gravity filtering, false to disableExample:
// Remove gravity from readings
Accelerometer.setGravityFilter(true);Note: iOS removes approximately 1.0 G from the Z-axis, while Android removes approximately 9.81 m/s² from the Z-axis.
setLowPassFilter(value: number): voidSets the low-pass filter coefficient. Low-pass filters smooth out rapid changes, useful for removing noise.
Parameters:
value - Filter coefficient between 0.0 and 1.00.0 = No filtering (raw data)1.0 = Maximum smoothingExample:
// Apply moderate smoothing
Accelerometer.setLowPassFilter(0.5);setHighPassFilter(value: number): voidSets the high-pass filter coefficient. High-pass filters remove slow changes, useful for detecting quick movements.
Parameters:
value - Filter coefficient between 0.0 and 1.00.0 = No filtering1.0 = Maximum filtering of slow changesExample:
// Filter out slow movements
Accelerometer.setHighPassFilter(0.5);addListener(callback): SubscriptionSubscribes to accelerometer updates.
Parameters:
callback - Function called when new data is availableReturns: Subscription object with a remove() method
Example:
const subscription = Accelerometer.addListener((data) => {
console.log('Acceleration:', data);
});
// Later, to unsubscribe:
subscription.remove();removeAllListeners(): voidRemoves all active listeners.
Example:
Accelerometer.removeAllListeners();AccelerometerDatainterface AccelerometerData {
x: number; // Acceleration on X-axis
y: number; // Acceleration on Y-axis
z: number; // Acceleration on Z-axis
timestamp: number; // Timestamp in milliseconds
}Coordinate System:
import * as Accelerometer from 'react-native-accelerometer';
// Configure filters
Accelerometer.setUpdateInterval(50); // 20 updates/second
Accelerometer.setGravityFilter(true); // Remove gravity
Accelerometer.setLowPassFilter(0.3); // Smooth data
// Start listening
Accelerometer.startUpdates();
const subscription = Accelerometer.addListener((data) => {
console.log('Filtered acceleration:', data);
});import * as Accelerometer from 'react-native-accelerometer';
const SHAKE_THRESHOLD = 2.5;
Accelerometer.setUpdateInterval(100);
Accelerometer.startUpdates();
const subscription = Accelerometer.addListener((data) => {
const { x, y, z } = data;
const acceleration = Math.sqrt(x * x + y * y + z * z);
if (acceleration > SHAKE_THRESHOLD) {
console.log('Device shaken!');
}
});import * as Accelerometer from 'react-native-accelerometer';
Accelerometer.setUpdateInterval(16); // ~60fps
Accelerometer.setGravityFilter(true);
Accelerometer.setLowPassFilter(0.5);
Accelerometer.startUpdates();
const subscription = Accelerometer.addListener((data) => {
// Use data.x and data.y to control game character
moveCharacter(data.x * 10, data.y * 10);
});If you encounter linker errors related to CoreMotion, make sure you've run:
cd ios && pod installMake sure your device has an accelerometer. You can check with:
const available = await Accelerometer.isAvailable();If you're experiencing high battery usage:
setUpdateInterval(200) or higherstopUpdates()This package is built with React Native's New Architecture:
MIT © Isaías Chávez Martínez
Made with create-react-native-library