Reputation: 91
I am using react-native and I want to count the steps of the user like Samsung Health step indicator.
I am using react-native-sensors library to access accelerometer data.
I followed this tutorial for pedometer algorithm, implemented in react-native.
import {View, Text} from 'react-native';
import {
accelerometer,
SensorTypes,
setUpdateIntervalForType,
} from 'react-native-sensors';
setUpdateIntervalForType(SensorTypes.accelerometer, 400);
const App = () => {
const [xAcceleration, setXAcceleration] = useState(0);
const [yAcceleration, setYAcceleration] = useState(0);
const [zAcceleration, setZAcceleration] = useState(0);
const [magnitudePrevious, setMagnitudePrevious] = useState(0);
const [steps, setSteps] = useState(0);
useEffect(() => {
const subscription = accelerometer
.pipe(data => data)
.subscribe(speed => {
setXAcceleration(speed.x);
setYAcceleration(speed.y);
setZAcceleration(speed.z);
});
return () => {
subscription.unsubscribe();
};
}, []);
useEffect(() => {
const magnitude = Math.sqrt(
Math.pow(xAcceleration, 2) +
Math.pow(yAcceleration, 2) +
Math.pow(zAcceleration, 2),
);
const magnitudeDelta = magnitude - magnitudePrevious;
setMagnitudePrevious(() => magnitude);
// I tried magnitudeDelta > 6, magnitudeDelta > 4,
// magnitudeDelta > 2, magnitudeDelta > 10 but didn't work properly
if (magnitudeDelta > 2) setSteps(prevSteps => prevSteps + 1);
}, [xAcceleration, yAcceleration, zAcceleration]);
return (
<View>
<Text>{steps}</Text>
</View>
)
}
If a shake my phone upwards or sideways it increments the steps but I think it's ok because samething happens in Samsung Health. But the main problem is it is not as accurate as Samsung Health when you walk.
For example: If a stepped 20 times it only counts 8 of them. I want it to be close to actual value.
Upvotes: 1
Views: 644