
Security News
PodRocket Podcast: Inside the Recent npm Supply Chain Attacks
Socket CEO Feross Aboukhadijeh discusses the recent npm supply chain attacks on PodRocket, covering novel attack vectors and how developers can protect themselves.
react-native-ahrs
Advanced tools
react-native-ahrs is an Attitude And Heading Reference System (AHRS) for React Native iOS and Android devices. It uses the device's internal sensors (accelerometer, gyroscope, magnetometer) to provide roll, pitch and magnetic heading in real-time.
It is implemented using C/C++, JSI (JavaScript Interface), and Turbo Modules for maximum performance and low latency.
yarn add react-native-ahrs
# iOS only
cd ios && pod install
Note: Ensure New Architecture is enabled in your app before using this library.
Basic example using hooks and a single listener:
import React, { useEffect, useState } from 'react';
import { View, Text } from 'react-native';
import { Ahrs, type AhrsData } from 'react-native-ahrs';
export default function Example() {
const [attitude, setAttitude] = useState<AhrsData>({
roll: 0,
pitch: 0,
heading: 0,
});
useEffect(() => {
// Register listener first
const unsubscribe = Ahrs.addListener(setAttitude);
// Start AHRS once a listener is registered
Ahrs.start();
// Optional configuration
Ahrs.setRate(20); // 1–60 Hz
Ahrs.setGain(3.0); // tune to preference/environment
return () => {
unsubscribe();
Ahrs.stop();
};
}, []);
return (
<View>
<Text>Pitch: {Math.round(attitude.pitch)}°</Text>
<Text>Roll: {Math.round(attitude.roll)}°</Text>
<Text>Heading: {Math.round(attitude.heading)}°</Text>
</View>
);
}
All functions are available on the Ahrs singleton. Below you will find detailed behavior, parameters, return values, and examples for each function.
Function | Description | Parameters | Returns / Notes |
---|---|---|---|
addListener(callback) | Subscribe to updates (roll, pitch, heading). | callback: (data: AhrsData) => void | Returns unsubscribe(): () => void. Auto-stops when last listener unsubscribes. |
removeAllListeners() | Remove all listeners and stop AHRS. | — | Safe to call anytime. |
start() | Start native sensor fusion and emit updates. | — | No-op with warning if no listeners registered. |
stop() | Stop native processing and updates. | — | Idempotent. |
reset() | Reinitialize AHRS internal state. | — | Keeps rate/gain; useful after disturbances. |
level() | Zero pitch and roll relative to current pose. | — | Heading unchanged. |
setRate(newRate) | Set update rate (Hz). | newRate: number (1–60) | Values outside 1–60 warn and are ignored. |
setGain(gain) | Set complementary filter gain. | gain: number | Typical start: 3.0; higher = more accel/mag influence. |
setRotation(rotation) | Apply extra 90° step rotation for UI alignment. | rotation: 'none','left' ,'right' | Use with your orientation/locking logic. |
getStatus() | Get JS-side status. | — | { isRunning: boolean, listenerCount: number } |
isSupported() | Check if required sensors are available. | — | Promise. Useful to gate features or show guidance. |
const unsubscribe = Ahrs.addListener(({ roll, pitch, heading }) => {
// Use values here; keep it fast
console.log('AHRS:', Math.round(roll), Math.round(pitch), Math.round(heading));
});
// later
unsubscribe();
// E.g., on logout or screen unmount
Ahrs.removeAllListeners();
const unsubscribe = Ahrs.addListener((data) => {/* ... */});
try {
Ahrs.start();
} catch (e) {
console.error('Failed to start AHRS', e);
}
// ... later
unsubscribe();
Ahrs.stop();
// On screen blur/unmount
Ahrs.stop();
// After a significant movement or to rebaseline
Ahrs.reset();
// Bind to a "Level" button when the device is stationary
Ahrs.level();
Ahrs.setRate(20);
Ahrs.setGain(3.0);
Ahrs.setRotation('left');
const { isRunning, listenerCount } = Ahrs.getStatus();
console.log(`AHRS running: ${isRunning}, listeners: ${listenerCount}`);
const supported = await Ahrs.isSupported();
if (!supported) {
Alert.alert('AHRS not supported', 'This device lacks required sensors.');
return;
}
// proceed to add listener and start
react-native-ahrs uses the revised AHRS algorithm presented in chapter 7 of Madgwick's PhD thesis.
This is a different algorithm to the better-known initial AHRS algorithm presented in chapter 3, commonly referred to as the "Madgwick algorithm".
For further background, reference implementations, and additional documentation, see the xioTechnologies Fusion library: xioTechnologies/Fusion.
The algorithm calculates the orientation as the integration of the gyroscope summed with a feedback term. The feedback term is equal to the error in the current measurement of orientation as determined by the other sensors, multiplied by a gain. The algorithm therefore functions as a complementary filter that combines high-pass filtered gyroscope measurements with low-pass filtered measurements from other sensors with a corner frequency determined by the gain. A low gain will 'trust' the gyroscope more and so be more susceptible to drift. A high gain will increase the influence of other sensors and the errors that result from accelerations and magnetic distortions. A gain of zero will ignore the other sensors so that the measurement of orientation is determined by only the gyroscope.
See the example app in example/ for a complete UI demonstrating rate, gain and rotation controls.
If you need any specific function from react-native-ahrs, please request it through an issue and it will implemented in the nearest time, or feel free to open a PR and it will be added to the library promptly.
See the contributing guide to learn how to contribute to the repository and the development workflow.
MIT
Made with create-react-native-library
FAQs
Attitude Heading Reference System for React-Native
We found that react-native-ahrs demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Socket CEO Feross Aboukhadijeh discusses the recent npm supply chain attacks on PodRocket, covering novel attack vectors and how developers can protect themselves.
Security News
Maintainers back GitHub’s npm security overhaul but raise concerns about CI/CD workflows, enterprise support, and token management.
Product
Socket Firewall is a free tool that blocks malicious packages at install time, giving developers proactive protection against rising supply chain attacks.