-
-
Save JeancarloBarrios/9cffddcbf60b7a878f2de37c9891644d to your computer and use it in GitHub Desktop.
POC accelerometer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Sample React Native App | |
* https://github.com/facebook/react-native | |
* | |
* @format | |
*/ | |
import React, { useEffect, useState } from 'react'; | |
import type { PropsWithChildren } from 'react'; | |
import { | |
SafeAreaView, | |
StyleSheet, | |
Text, | |
useColorScheme, | |
} from 'react-native'; | |
import { | |
Colors, | |
} from 'react-native/Libraries/NewAppScreen'; | |
import { | |
accelerometer, | |
setUpdateIntervalForType, | |
SensorTypes, | |
} from 'react-native-sensors'; | |
type SectionProps = PropsWithChildren<{ | |
title: string; | |
}>; | |
const toDegrees = (angle: any) => angle * (180 / Math.PI); | |
const calculateInclination = (x: number, y: number, z: number): Inclination => { | |
const norm = Math.sqrt(x * x + y * y + z * z); | |
const pitch = (Math.asin(-x / norm) * 180) / Math.PI; | |
const roll = (Math.atan2(y, z) * 180) / Math.PI; | |
return { pitch, roll }; | |
}; | |
interface AccelerometerData { | |
x: number; | |
y: number; | |
z: number; | |
timestamp: number; | |
} | |
interface Inclination { | |
pitch: number; | |
roll: number; | |
} | |
function App(): JSX.Element { | |
const [inclination, setInclination] = useState<Inclination>({ pitch: 0, roll: 0 }); | |
useEffect(() => { | |
setUpdateIntervalForType(SensorTypes.gyroscope, 50); // defaults to 100ms | |
const subscription = accelerometer.subscribe((data: AccelerometerData) => { | |
const angle = calculateInclination(data.x, data.y, data.z); | |
setInclination({ pitch: parseFloat(angle.pitch.toFixed(0)), roll: parseFloat(angle.roll.toFixed(0)) }); | |
}); | |
}, []) | |
const isDarkMode = useColorScheme() === 'light'; | |
const backgroundStyle = { | |
backgroundColor: isDarkMode ? Colors.darker : Colors.lighter, | |
}; | |
return ( | |
<SafeAreaView style={backgroundStyle}> | |
<Text style={styles.text}>Inclination:</Text> | |
<Text style={styles.text}>Pitch: {inclination.pitch}°</Text> | |
<Text style={styles.text}>Roll: {inclination.roll}°</Text> | |
</SafeAreaView> | |
); | |
} | |
const styles = StyleSheet.create({ | |
container: { | |
flex: 1, | |
justifyContent: 'center', | |
alignItems: 'center', | |
}, | |
text: { | |
fontSize: 30, | |
marginBottom: 10, | |
}, | |
}); | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment