Using Android phones Magnetic Field sensor I am able to get a value depending on Z-Rotation. So if Z-Rotation is a positive value, so will this value (x) be.
private SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent sensorEvent) {
float x = sensorEvent.values[0];
}
@Override
public void onAccuracyChanged(Sensor sensor, int i) {}
};
I would like to measure how much time that passes while value (x) is positive or negative.
For example:
Results:
positive_value_time = 2 seconds
negative_value_time = 1 seconds
How would I go about and implement this?
I have not tested this on a real device, but the following should work. This always keeps track of the previous event and then determines the amount of time spent between those events while x was negative or positive. Then it adjusts negativeTime
and positiveTime
accordingly.
import android.hardware.SensorEventListener;
import android.hardware.SensorEvent;
public class SensorMonitor implements SensorEventListener {
SensorEvent e0;
SensorEvent e1;
long positiveTime; // positive value time in nanoseconds
long negativeTime; // negative value time in nanoseconds
SensorMonitor() {
this.e0 = null;
this.e1 = null;
this.positiveTime = 0;
this.negativeTime = 0;
}
@Override
public void onSensorChanged(SensorEvent sensorEvent) {
if (this.e0 == null) {
this.e0 = sensorEvent;
return;
}
this.e1 = sensorEvent;
float x0 = this.e0.values[0];
float x1 = this.e1.values[0];
float dx = Math.abs(x1 - x0);
long t0 = this.e0.timestamp;
long t1 = this.e1.timestamp;
long dt = t1 - t0;
if (x0 <= 0 && x1 <= 0) {
this.negativeTime += dt;
} else if (x0 >= 0 && x1 >= 0) {
this.positiveTime += dt;
} else if (x0 <= 0 && x1 >= 0){
float tn = dt/dx * Math.abs(x0);
float tp = dt/dx * x1;
this.positiveTime += tp;
this.negativeTime += tn;
} else {
float tn = dt/dx * Math.abs(x1);
float tp = dt/dx * x0;
this.positiveTime += tp;
this.negativeTime += tn;
}
this.e0 = this.e1;
}
// returns positive time in seconds
public float getPositiveTime() {
return (float)this.positiveTime / (float)Math.pow(10,9);
}
// returns negative time in seconds
public float getNegativeTime() {
return (float)this.negativeTime / (float)Math.pow(10,9);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.