I am using react-native-sensors for getting accelerometer readings. It is reading the sensor values correctly. Being new to React Native, I couldn't figure out how to add codes to calculate the acceleration vector inside the sensor.subscribe method.
import {
setUpdateIntervalForType,
SensorTypes,
accelerometer,
gyroscope
} from 'react-native-sensors';
........
export default class Accelerometer extends Component {
constructor(props) {
super(props);
setUpdateIntervalForType(SensorTypes.accelerometer, 200);
this.accelSubscription = accelerometer.subscribe(({ x, y, z, timestamp }) =>
this.setState({
accel_x: x,
accel_y: y,
accel_z: z,
})
);
this.state = {
acceleration: 0,
accel_x: 0,
accel_y: 0,
accel_z: 0,
};
}
And here's the calculation codes I want to perform whenever I get new accelerometer readings:
const accelx = this.state.accel_x;
const accely = this.state.accel_y;
const accelz = this.state.accel_z;
const lastAccel = this.state.acceleration;
const currAcceleration = Math.sqrt((accelx * accelx) + (accely * accely) + (accelz * accelz));
//I need to delta value to detect changes
const accelerationDelta = currAcceleration - lastAccel;
this.setState({
acceleration: currAcceleration,
});
If I put the codes directly inside the accelerometer.subscribe() it will throw error. How can I accomplish this?
You should put your code inside brackets.
In arrow function if you don't use {}
then you can only write one line
accelerometer.subscribe(({ x, y, z, timestamp }) =>{
this.setState({ accel_x: x });
alert('Test this');
}