I’m trying to find out the force of which a button is pressed with the on-board accelerometer.
I figured i’ll have to do a series of readings and then compare the values.
My attempt at it was something like this:
velButton.setOnTouchListener(new OnTouchListener()
{
public boolean onTouch(View view, MotionEvent event)
{
int velocity = 0;
switch (event.getAction())
{
case MotionEvent.ACTION_DOWN:
velocity = getVelocity();
velocityView.setText("This is the velocity: " + velocity);
break;
}
return false;
});
}
protected int getVelocity()
{
float accent = 0;
int velocity;
try
{
accent = getHighestValue();
} catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
velocity = (int) accent;
return velocity;
}
protected float getHighestValue() throws InterruptedException
{
float highest;
float[] value = new float[20];
String txt = "";
for(int i = 0; i < value.length; i++)
{
Thread.sleep(1);
value[i] = accelerometer_z;
txt += "Reading at: " + i + " ms returns: " + value[i] + "\n";
}
Arrays.sort(value);
highest = value[19];
textView2.setText(txt);
return highest;
}
The float accelerometer_z is initialized in my main activity and is updated continually through onSensorChanged.
My problem here is that I don’t get a series of values, I only get One value from the for-loop in my getHighestValue method.
Cheers
/M
Added onSensorChanged:
@Override
public void onSensorChanged(SensorEvent event)
{
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER)
{
getAccelerometer(event);
}
}
private void getAccelerometer(SensorEvent event)
{
float[] value = event.values;
// Movement
accelerometer_x = value[0];
accelerometer_y = value[1];
accelerometer_z = value[2];
accelationSquareRoot = (accelerometer_x * accelerometer_x + accelerometer_y *
accelerometer_y + accelerometer_z * accelerometer_z)
/ (SensorManager.GRAVITY_EARTH * SensorManager.GRAVITY_EARTH);
long actualTime = System.currentTimeMillis();
if (accelationSquareRoot >= 2)
{
if (actualTime - lastUpdate < 200)
{
return;
}
lastUpdate = actualTime;
}
}
It seems that only one event handler can be run at the same time and that’s the reason why I’m only getting a single value from the gethighestValue.
The onSensorChanged will never be allowed to make a new reading as long as the motionEvent in the onTouch is waiting for new input.
I solved this by letting the onSensorChanged implement a method like this:
accReadingZ is here a class member with a size of 10 elements.
I can now use Collections.max(accReadingZ) to get the highest value in the series of readings.