I want to use my phone's accelerometer and gyroscope and store the data in a file (finally csv). Currently I am using the following code in onSensorChanged Function
override fun onSensorChanged(event: SensorEvent?) {
if (event != null) {
val timeInMills = System.currentTimeMillis() + (event.timestamp - SystemClock.elapsedRealtimeNanos()) / 1000000
binding.tvShowDataTime.text = (timeInMills / 1000).toString()
var accData = ""
var gyroData = ""
if (event.sensor.type == Sensor.TYPE_ACCELEROMETER) {
accData += "${event!!.values[0]}," +
"${event!!.values[1]}," +
"${event!!.values[2]},"
}
if (event.sensor.type == Sensor.TYPE_GYROSCOPE) {
gyroData += "${event!!.values[0]}," +
"${event!!.values[1]}," +
"${event!!.values[2]},"
}
val data = accData + gyroData + "\n"
Log.d("DataSensor", data)
writer.appendText(data)
}
the output that I am getting in the file is as following
-0.01585245,-0.09661021,9.810872,
-9.162709E-4,1.5271181E-4,0.0015271181,
-0.012562319,-0.09421739,9.824033,
-0.0010689828,-6.1084726E-4,0.0012216945,
it is comming alternatingly on new lines
e.g.
accelerometer(x,y,z,)
gyroscope(x,y,z,)
accelerometer(x,y,z,)
gyroscope(x,y,z,) ......
but I want accelerometer and gyroscope on same line ax,ay,az,gx,gy,gz
how can I do it?
My suggestion is to bring in some architecture into this.
Try to separate your onSensorChanged method from the "write-file" method. You should then be able to see how to write the "combination"-function.
Suggestion for your "combination"-function:
Let your onSensorChanged-Method return/set you the a specific value. I would assume that your values are calling cyclic (and in same order) your onSensorChanged-Method? So it would be easy to just await if both values (modulo counter or boolean-flag if only 2 sensors) got updated and then fire your write-function based on this condition.