I'm sampling accelerometer sensor and present a graph in real time, using Graph View
library (4.0.1).
The app is working well except the graph is wrong:
As you can see in the picture, Z axis (magenta color) has value of ~9.8 but in the graph it's shows as ~15, Y axis (green color) has value of 0.2 but in the graph us under the zero and same idea with X axis.
Here is my code:
SensorManager sensorManager;
TextView tvX, tvY, tvZ;
GraphView graph;
LineGraphSeries<DataPoint> seriesX, seriesY, seriesZ;
long startTime;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_runtime_graph);
tvX = (TextView) findViewById(R.id.tvAcc_X); // color : blue
tvY = (TextView) findViewById(R.id.tvAcc_Y); // color : green
tvZ = (TextView) findViewById(R.id.tvAcc_Z); // color : magenta
graph = (GraphView) findViewById(R.id.graph);
seriesX = new LineGraphSeries<>();
seriesY = new LineGraphSeries<>();
seriesZ = new LineGraphSeries<>();
seriesX.setColor(Color.BLUE);
seriesY.setColor(Color.GREEN);
seriesZ.setColor(Color.MAGENTA);
graph.addSeries(seriesX);
graph.addSeries(seriesY);
graph.addSeries(seriesZ);
startTime = System.nanoTime() / 100000000;
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
}
@Override
public void onSensorChanged(SensorEvent event)
{
tvX.setText(String.valueOf(event.values[0]));
tvY.setText(String.valueOf(event.values[1]));
tvZ.setText(String.valueOf(event.values[2]));
updateGraph((event.timestamp / 100000000) - startTime,
event.values[0], event.values[1], event.values[2]);
}
void updateGraph (final long timestamp, final float x, final float y, final float z)
{
runOnUiThread(new Runnable() {
@Override
public void run() {
seriesX.appendData(new DataPoint(timestamp, x), true, 40);
seriesY.appendData(new DataPoint(timestamp, y), true, 40);
seriesZ.appendData(new DataPoint(timestamp, z), true, 40);
}
});
}
I found the issue happened when scrollToEnd
field is set to true
, otherwise the graph is right. Another issue I found that may be related, the axis are not update when scro;lToEnd
is true.
How can I beat the problem?
logcat shows why scrollToEnd does not work in your case:
GraphView: scrollToEnd works only with manual x axis bounds
to set the x axis bounds manual, add this code in your create method
Viewport vp = graph.getViewport();
vp.setXAxisBoundsManual(true);
vp.setMinX(0);
vp.setMaxX(1000);
but there is another issue with the code: System.nanoTime() and event.timestamp are different time formats
System.nanoTime() // current value of system timer in nanoseconds
event.timestamp // nanoseconds since device uptime
This is not very well documented: SensorEvent timestamp
See also: Accelerometer SensorEvent timestamp