Getting Started with Accelerometer
This guide will walk you through integrating the Capacitor Accelerometer plugin into your application.
Installation
Section titled âInstallationâInstall the plugin using npm:
npm install @capgo/capacitor-accelerometernpx cap syncPlatform Configuration
Section titled âPlatform ConfigurationâNo additional configuration required. The accelerometer is always available.
Android
Section titled âAndroidâNo additional configuration required. The accelerometer is always available.
The plugin uses the DeviceMotion API. Requires HTTPS in production.
Basic Usage
Section titled âBasic UsageâImport the Plugin
Section titled âImport the Pluginâimport { Accelerometer } from '@capgo/capacitor-accelerometer';Start Monitoring
Section titled âStart Monitoringâconst startAccelerometer = async () => { await Accelerometer.start({ interval: 100 // Update interval in milliseconds });
console.log('Accelerometer started');};Listen to Acceleration Events
Section titled âListen to Acceleration EventsâAccelerometer.addListener('accelerationChange', (data) => { console.log('X:', data.x); console.log('Y:', data.y); console.log('Z:', data.z); console.log('Timestamp:', data.timestamp);});Get Current Reading
Section titled âGet Current Readingâconst getCurrentAcceleration = async () => { const reading = await Accelerometer.getCurrentAcceleration(); console.log('Current acceleration:', reading);};Stop Monitoring
Section titled âStop Monitoringâconst stopAccelerometer = async () => { await Accelerometer.stop(); console.log('Accelerometer stopped');};Complete Example
Section titled âComplete ExampleâHereâs a complete example with shake detection:
import { Accelerometer } from '@capgo/capacitor-accelerometer';
class AccelerometerService { private listener: any; private lastX = 0; private lastY = 0; private lastZ = 0; private shakeThreshold = 15;
async initialize() { await Accelerometer.start({ interval: 100 });
this.listener = Accelerometer.addListener('accelerationChange', (data) => { this.handleAcceleration(data); }); }
handleAcceleration(data: any) { // Calculate delta const deltaX = Math.abs(data.x - this.lastX); const deltaY = Math.abs(data.y - this.lastY); const deltaZ = Math.abs(data.z - this.lastZ);
// Check for shake if (deltaX > this.shakeThreshold || deltaY > this.shakeThreshold || deltaZ > this.shakeThreshold) { this.onShake(); }
// Update last values this.lastX = data.x; this.lastY = data.y; this.lastZ = data.z;
// Update UI this.updateDisplay(data); }
onShake() { console.log('Device shaken!'); // Trigger shake action }
updateDisplay(data: any) { console.log(`X: ${data.x.toFixed(2)} m/s²`); console.log(`Y: ${data.y.toFixed(2)} m/s²`); console.log(`Z: ${data.z.toFixed(2)} m/s²`);
// Calculate magnitude const magnitude = Math.sqrt( data.x * data.x + data.y * data.y + data.z * data.z ); console.log(`Magnitude: ${magnitude.toFixed(2)} m/s²`); }
async cleanup() { if (this.listener) { this.listener.remove(); } await Accelerometer.stop(); }}
// Usageconst accelService = new AccelerometerService();accelService.initialize();
// Cleanup when done// accelService.cleanup();Understanding Readings
Section titled âUnderstanding ReadingsâAcceleration Axes
Section titled âAcceleration Axesâ- X-axis: Left (-) to Right (+)
- Y-axis: Bottom (-) to Top (+)
- Z-axis: Back (-) to Front (+)
Gravity
Section titled âGravityâ- Device at rest shows ~9.8 m/s² on one axis (gravity)
- Moving device shows acceleration in addition to gravity
- Measured in meters per second squared (m/s²)
- Gravity = 9.8 m/s²
Common Use Cases
Section titled âCommon Use CasesâShake Detection
Section titled âShake Detectionâclass ShakeDetector { private lastUpdate = 0; private lastX = 0; private lastY = 0; private lastZ = 0;
detectShake(x: number, y: number, z: number): boolean { const currentTime = Date.now();
if (currentTime - this.lastUpdate > 100) { const deltaX = Math.abs(x - this.lastX); const deltaY = Math.abs(y - this.lastY); const deltaZ = Math.abs(z - this.lastZ);
this.lastUpdate = currentTime; this.lastX = x; this.lastY = y; this.lastZ = z;
return deltaX + deltaY + deltaZ > 15; }
return false; }}Tilt Detection
Section titled âTilt Detectionâclass TiltDetector { getTiltAngles(x: number, y: number, z: number) { const roll = Math.atan2(y, z) * (180 / Math.PI); const pitch = Math.atan2(-x, Math.sqrt(y * y + z * z)) * (180 / Math.PI);
return { roll, pitch }; }
isDeviceFlat(z: number): boolean { return Math.abs(z - 9.8) < 1.0; }
isDeviceUpright(y: number): boolean { return Math.abs(y - 9.8) < 2.0; }}Step Counter
Section titled âStep Counterâclass StepCounter { private steps = 0; private lastMagnitude = 0; private threshold = 11;
processAcceleration(x: number, y: number, z: number) { const magnitude = Math.sqrt(x * x + y * y + z * z);
if (magnitude > this.threshold && this.lastMagnitude < this.threshold) { this.steps++; console.log('Steps:', this.steps); }
this.lastMagnitude = magnitude; }}Best Practices
Section titled âBest Practicesâ-
Choose Appropriate Intervals: Balance responsiveness and battery life
- Gaming: 16-50ms
- Fitness: 100-200ms
- General: 200-500ms
-
Remove Listeners: Always clean up when done
-
Filter Noise: Use moving averages for smoother data
-
Consider Battery: High-frequency polling drains battery
-
Test on Real Devices: Simulators donât provide accurate data
Performance Tips
Section titled âPerformance TipsâDebouncing
Section titled âDebouncingâclass AccelerometerDebouncer { private timeout: any;
debounce(callback: Function, delay: number) { return (...args: any[]) => { clearTimeout(this.timeout); this.timeout = setTimeout(() => callback(...args), delay); }; }}Data Smoothing
Section titled âData Smoothingâclass AccelerometerFilter { private alpha = 0.8; private filteredX = 0; private filteredY = 0; private filteredZ = 0;
filter(x: number, y: number, z: number) { this.filteredX = this.alpha * x + (1 - this.alpha) * this.filteredX; this.filteredY = this.alpha * y + (1 - this.alpha) * this.filteredY; this.filteredZ = this.alpha * z + (1 - this.alpha) * this.filteredZ;
return { x: this.filteredX, y: this.filteredY, z: this.filteredZ }; }}Next Steps
Section titled âNext Stepsâ- Explore the API Reference for complete method documentation
- Check out the example app for advanced usage
- See the tutorial for complete implementation examples