#
i want to try counting shake on android and show it on textview, but keep crashing after i try shaking.
here's my code.
private final SensorEventListener mSensorListener = new SensorEventListener() {
public void onSensorChanged(SensorEvent se) {
float x = se.values[0];
float y = se.values[1];
float z = se.values[2];
mAccelLast = mAccelCurrent;
mAccelCurrent = (float) Math.sqrt((double) (x * x + y * y + z * z));
float delta = mAccelCurrent - mAccelLast;
mAccel = mAccel * 0.9f + delta; // perform low-cut filter
if (mAccel > 10) {
max = 100;
for (i=1; i<=max;) {
i=i+1;
TextView angka = (TextView) findViewById(R.id.angka);
angka.setText(i);
}
}
}
Related
I want to detect whether device is moving or device is stationary. I have a situation where i want to execute task when device is not moving.
Right now i have implemented something like this using sensor but i'm not getting device is moving when i try to move device on plain surface like table.
#Override
public void onSensorChanged(SensorEvent sensorEvent) {
double alpha = 0.6;
double[] gravity = new double[3];
gravity[0] = 0;
gravity[1] = 0;
gravity[2] = 0;
gravity[0] = alpha * gravity[0] + (1 - alpha) * sensorEvent.values[0];
gravity[1] = alpha * gravity[1] + (1 - alpha) * sensorEvent.values[1];
gravity[2] = alpha * gravity[2] + (1 - alpha) * sensorEvent.values[2];
double[] linear_acceleration = new double[3];
linear_acceleration[0] = sensorEvent.values[0] - gravity[0];
linear_acceleration[1] = sensorEvent.values[1] - gravity[1];
linear_acceleration[2] = sensorEvent.values[2] - gravity[2];
float magnitude = 0.0f;
magnitude = (float)Math.sqrt(linear_acceleration[0]*linear_acceleration[0]+linear_acceleration[1]*linear_acceleration[1]+linear_acceleration[2]*linear_acceleration[2]);
magnitude = Math.abs(magnitude);
Log.e("Magnitude",magnitude+"");
if(magnitude>0.2){
Log.e("walking","Yes");
}else{
Log.e("walking","No");
}
}
If you are looking for an example there is one below
This code is for walking detection
to get smoother value.
// initialize
private SensorManager sensorMan;
private Sensor accelerometer;
private float[] mGravity;
private double mAccel;
private double mAccelCurrent;
private double mAccelLast;
private boolean sensorRegistered = false;
// onCreate
sensorMan = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
accelerometer = sensorMan.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
mAccel = 0.00f;
mAccelCurrent = SensorManager.GRAVITY_EARTH;
mAccelLast = SensorManager.GRAVITY_EARTH;
sensorMan.registerListener(this, accelerometer,
SensorManager.SENSOR_DELAY_NORMAL);
sensorRegistered = true;
// onSensorChanged
private int hitCount = 0;
private double hitSum = 0;
private double hitResult = 0;
private final int SAMPLE_SIZE = 50; // change this sample size as you want, higher is more precise but slow measure.
private final double THRESHOLD = 0.2; // change this threshold as you want, higher is more spike movement
#Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
mGravity = event.values.clone();
// Shake detection
double x = mGravity[0];
double y = mGravity[1];
double z = mGravity[2];
mAccelLast = mAccelCurrent;
mAccelCurrent = Math.sqrt(x * x + y * y + z * z);
double delta = mAccelCurrent - mAccelLast;
mAccel = mAccel * 0.9f + delta;
if (hitCount <= SAMPLE_SIZE) {
hitCount++;
hitSum += Math.abs(mAccel);
} else {
hitResult = hitSum / SAMPLE_SIZE;
Log.d(TAG, String.valueOf(hitResult));
if (hitResult > THRESHOLD) {
Log.d(TAG, "Walking");
} else {
Log.d(TAG, "Stop Walking");
}
hitCount = 0;
hitSum = 0;
hitResult = 0;
}
}
}
I am new in android developing, I developed this code based on previous code related to Mr.liwatiz to find orientation from sensor fusion, I added writeCSV file to store data, The application work and the file created but there is no data store! So please what is the problem. my code clear below
public class MainActivity extends Activity implements SensorEventListener, RadioGroup.OnCheckedChangeListener{
private SensorManager mSensorManager = null;
// angular speeds from gyro
private float[] gyro = new float[3];
// rotation matrix from gyro data
private float[] gyroMatrix = new float[9];
// orientation angles from gyro matrix
private float[] gyroOrientation = new float[3];
// magnetic field vector
private float[] magnet = new float[3];
// accelerometer vector
private float[] accel = new float[3];
// orientation angles from accel and magnet
private float[] accMagOrientation = new float[3];
// final orientation angles from sensor fusion
private float[] fusedOrientation = new float[3];
// accelerometer and magnetometer based rotation matrix
private float[] rotationMatrix = new float[9];
public static final float EPSILON = 0.000000001f;
private static final float NS2S = 1.0f / 1000000.0f;
private int timestamp;
private boolean initState = true;
public static final int TIME_CONSTANT = 30;
public static final float FILTER_COEFFICIENT = 0.98f;
private Timer fuseTimer = new Timer();
// The following members are only for displaying the sensor output.
public Handler mHandler;
private RadioGroup mRadioGroup;
private TextView mAzimuthView;
private TextView mPitchView;
private TextView mRollView;
private int radioSelection;
DecimalFormat d = new DecimalFormat("#.##");
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gyroOrientation[0] = 0.0f;
gyroOrientation[1] = 0.0f;
gyroOrientation[2] = 0.0f;
// initialise gyroMatrix with identity matrix
gyroMatrix[0] = 1.0f; gyroMatrix[1] = 0.0f; gyroMatrix[2] = 0.0f;
gyroMatrix[3] = 0.0f; gyroMatrix[4] = 1.0f; gyroMatrix[5] = 0.0f;
gyroMatrix[6] = 0.0f; gyroMatrix[7] = 0.0f; gyroMatrix[8] = 1.0f;
// get sensorManager and initialise sensor listeners
mSensorManager = (SensorManager) this.getSystemService(SENSOR_SERVICE);
initListeners();
// wait for one second until gyroscope and magnetometer/accelerometer
// data is initialised then scedule the complementary filter task
fuseTimer.scheduleAtFixedRate(new calculateFusedOrientationTask(),
1000, TIME_CONSTANT);
// GUI stuff
mHandler = new Handler();
radioSelection = 0;
d.setRoundingMode(RoundingMode.HALF_UP);
d.setMaximumFractionDigits(3);
d.setMinimumFractionDigits(3);
mRadioGroup = (RadioGroup)findViewById(R.id.radioGroup1);
mAzimuthView = (TextView)findViewById(R.id.textView4);
mPitchView = (TextView)findViewById(R.id.textView5);
mRollView = (TextView)findViewById(R.id.textView6);
mRadioGroup.setOnCheckedChangeListener(this);
}
#Override
public void onStop() {
super.onStop();
// unregister sensor listeners to prevent the activity from draining the device's battery.
mSensorManager.unregisterListener(this);
}
#Override
protected void onPause() {
super.onPause();
// unregister sensor listeners to prevent the activity from draining the device's battery.
mSensorManager.unregisterListener(this);
}
#Override
public void onResume() {
super.onResume();
// restore the sensor listeners when user resumes the application.
initListeners();
}
// This function registers sensor listeners for the accelerometer, magnetometer and gyroscope.
public void initListeners(){
mSensorManager.registerListener(this,
mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_NORMAL);
mSensorManager.registerListener(this,
mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE),
SensorManager.SENSOR_DELAY_NORMAL);
mSensorManager.registerListener(this,
mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD),
SensorManager.SENSOR_DELAY_NORMAL);
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
public void writeToCsvGy(String x,String y,String z) throws IOException {
Calendar c = Calendar.getInstance();
File folder = new File(Environment.getExternalStorageDirectory() + "/TollCulator");
boolean success = true;
if (!folder.exists()) {
success = folder.mkdir();
}
if (success) {
// Do something on success
String csv = "/storage/sdcard0/project/GyroscopeValue.csv";
FileWriter file_writer = new FileWriter(csv,true);
String s= c.get(Calendar.YEAR)+","+c.get(Calendar.MONTH)+","+c.get(Calendar.DATE)+","+c.get(Calendar.HOUR)+","+c.get(Calendar.MINUTE)+","+c.get(Calendar.SECOND)+","+ c.get(Calendar.MILLISECOND)+","+x + ","+y+","+z+"\n";
file_writer.append(s);
file_writer.close();
}
}
#Override
public void onSensorChanged(SensorEvent event) {
switch(event.sensor.getType()) {
case Sensor.TYPE_ACCELEROMETER:
// copy new accelerometer data into accel array and calculate orientation
System.arraycopy(event.values, 0, accel, 0, 3);
calculateAccMagOrientation();
break;
case Sensor.TYPE_GYROSCOPE:
// process gyro data
gyroFunction(event);
break;
case Sensor.TYPE_MAGNETIC_FIELD:
// copy new magnetometer data into magnet array
System.arraycopy(event.values, 0, magnet, 0, 3);
break;
}
}
// calculates orientation angles from accelerometer and magnetometer output
public void calculateAccMagOrientation() {
if(SensorManager.getRotationMatrix(rotationMatrix, null, accel, magnet)) {
SensorManager.getOrientation(rotationMatrix, accMagOrientation);
}
}
// This function is borrowed from the Android reference
// at http://developer.android.com/reference/android/hardware/SensorEvent.html#values
// It calculates a rotation vector from the gyroscope angular speed values.
private void getRotationVectorFromGyro(float[] gyroValues,
float[] deltaRotationVector,
float timeFactor)
{
float[] normValues = new float[3];
// Calculate the angular speed of the sample
float omegaMagnitude =
(float)Math.sqrt(gyroValues[0] * gyroValues[0] +
gyroValues[1] * gyroValues[1] +
gyroValues[2] * gyroValues[2]);
// Normalize the rotation vector if it's big enough to get the axis
if(omegaMagnitude > EPSILON) {
normValues[0] = gyroValues[0] / omegaMagnitude;
normValues[1] = gyroValues[1] / omegaMagnitude;
normValues[2] = gyroValues[2] / omegaMagnitude;
}
// Integrate around this axis with the angular speed by the timestep
// in order to get a delta rotation from this sample over the timestep
// We will convert this axis-angle representation of the delta rotation
// into a quaternion before turning it into the rotation matrix.
float thetaOverTwo = omegaMagnitude * timeFactor;
float sinThetaOverTwo = (float)Math.sin(thetaOverTwo);
float cosThetaOverTwo = (float)Math.cos(thetaOverTwo);
deltaRotationVector[0] = sinThetaOverTwo * normValues[0];
deltaRotationVector[1] = sinThetaOverTwo * normValues[1];
deltaRotationVector[2] = sinThetaOverTwo * normValues[2];
deltaRotationVector[3] = cosThetaOverTwo;
}
// This function performs the integration of the gyroscope data.
// It writes the gyroscope based orientation into gyroOrientation.
public void gyroFunction(SensorEvent event) {
// don't start until first accelerometer/magnetometer orientation has been acquired
if (accMagOrientation == null)
return;
// initialisation of the gyroscope based rotation matrix
if(initState) {
float[] initMatrix = new float[9];
initMatrix = getRotationMatrixFromOrientation(accMagOrientation);
float[] test = new float[3];
SensorManager.getOrientation(initMatrix, test);
gyroMatrix = matrixMultiplication(gyroMatrix, initMatrix);
initState = false;
}
// copy the new gyro values into the gyro array
// convert the raw gyro data into a rotation vector
float[] deltaVector = new float[4];
if(timestamp != 0) {
final float dT = (event.timestamp - timestamp) * NS2S;
System.arraycopy(event.values, 0, gyro, 0, 3);
getRotationVectorFromGyro(gyro, deltaVector, dT / 2.0f);
}
// measurement done, save current time for next interval
switch ( timestamp = (int) event.timestamp ) {
}
// convert rotation vector into rotation matrix
float[] deltaMatrix = new float[9];
SensorManager.getRotationMatrixFromVector(deltaMatrix, deltaVector);
// apply the new rotation interval on the gyroscope based rotation matrix
gyroMatrix = matrixMultiplication(gyroMatrix, deltaMatrix);
// get the gyroscope based orientation from the rotation matrix
SensorManager.getOrientation(gyroMatrix, gyroOrientation);
}
private float[] getRotationMatrixFromOrientation(float[] o) {
float[] xM = new float[9];
float[] yM = new float[9];
float[] zM = new float[9];
float sinX = (float)Math.sin(o[1]);
float cosX = (float)Math.cos(o[1]);
float sinY = (float)Math.sin(o[2]);
float cosY = (float)Math.cos(o[2]);
float sinZ = (float)Math.sin(o[0]);
float cosZ = (float)Math.cos(o[0]);
// rotation about x-axis (pitch)
xM[0] = 1.0f; xM[1] = 0.0f; xM[2] = 0.0f;
xM[3] = 0.0f; xM[4] = cosX; xM[5] = sinX;
xM[6] = 0.0f; xM[7] = -sinX; xM[8] = cosX;
// rotation about y-axis (roll)
yM[0] = cosY; yM[1] = 0.0f; yM[2] = sinY;
yM[3] = 0.0f; yM[4] = 1.0f; yM[5] = 0.0f;
yM[6] = -sinY; yM[7] = 0.0f; yM[8] = cosY;
// rotation about z-axis (azimuth)
zM[0] = cosZ; zM[1] = sinZ; zM[2] = 0.0f;
zM[3] = -sinZ; zM[4] = cosZ; zM[5] = 0.0f;
zM[6] = 0.0f; zM[7] = 0.0f; zM[8] = 1.0f;
// rotation order is y, x, z (roll, pitch, azimuth)
float[] resultMatrix = matrixMultiplication(xM, yM);
resultMatrix = matrixMultiplication(zM, resultMatrix);
return resultMatrix;
}
private float[] matrixMultiplication(float[] A, float[] B) {
float[] result = new float[9];
result[0] = A[0] * B[0] + A[1] * B[3] + A[2] * B[6];
result[1] = A[0] * B[1] + A[1] * B[4] + A[2] * B[7];
result[2] = A[0] * B[2] + A[1] * B[5] + A[2] * B[8];
result[3] = A[3] * B[0] + A[4] * B[3] + A[5] * B[6];
result[4] = A[3] * B[1] + A[4] * B[4] + A[5] * B[7];
result[5] = A[3] * B[2] + A[4] * B[5] + A[5] * B[8];
result[6] = A[6] * B[0] + A[7] * B[3] + A[8] * B[6];
result[7] = A[6] * B[1] + A[7] * B[4] + A[8] * B[7];
result[8] = A[6] * B[2] + A[7] * B[5] + A[8] * B[8];
return result;
}
class calculateFusedOrientationTask extends TimerTask {
public void run() {
float oneMinusCoeff = 1.0f - FILTER_COEFFICIENT;
/*
* Fix for 179? <--> -179? transition problem:
* Check whether one of the two orientation angles (gyro or accMag) is negative while the other one is positive.
* If so, add 360? (2 * math.PI) to the negative value, perform the sensor fusion, and remove the 360? from the result
* if it is greater than 180?. This stabilizes the output in positive-to-negative-transition cases.
*/
// azimuth
if (gyroOrientation[0] < -0.5 * Math.PI && accMagOrientation[0] > 0.0) {
fusedOrientation[0] = (float) (FILTER_COEFFICIENT * (gyroOrientation[0] + 2.0 * Math.PI) + oneMinusCoeff * accMagOrientation[0]);
fusedOrientation[0] -= (fusedOrientation[0] > Math.PI) ? 2.0 * Math.PI : 0;
}
else if (accMagOrientation[0] < -0.5 * Math.PI && gyroOrientation[0] > 0.0) {
fusedOrientation[0] = (float) (FILTER_COEFFICIENT * gyroOrientation[0] + oneMinusCoeff * (accMagOrientation[0] + 2.0 * Math.PI));
fusedOrientation[0] -= (fusedOrientation[0] > Math.PI)? 2.0 * Math.PI : 0;
}
else {
fusedOrientation[0] = FILTER_COEFFICIENT * gyroOrientation[0] + oneMinusCoeff * accMagOrientation[0];
}
// pitch
if (gyroOrientation[1] < -0.5 * Math.PI && accMagOrientation[1] > 0.0) {
fusedOrientation[1] = (float) (FILTER_COEFFICIENT * (gyroOrientation[1] + 2.0 * Math.PI) + oneMinusCoeff * accMagOrientation[1]);
fusedOrientation[1] -= (fusedOrientation[1] > Math.PI) ? 2.0 * Math.PI : 0;
}
else if (accMagOrientation[1] < -0.5 * Math.PI && gyroOrientation[1] > 0.0) {
fusedOrientation[1] = (float) (FILTER_COEFFICIENT * gyroOrientation[1] + oneMinusCoeff * (accMagOrientation[1] + 2.0 * Math.PI));
fusedOrientation[1] -= (fusedOrientation[1] > Math.PI)? 2.0 * Math.PI : 0;
}
else {
fusedOrientation[1] = FILTER_COEFFICIENT * gyroOrientation[1] + oneMinusCoeff * accMagOrientation[1];
}
// roll
if (gyroOrientation[2] < -0.5 * Math.PI && accMagOrientation[2] > 0.0) {
fusedOrientation[2] = (float) (FILTER_COEFFICIENT * (gyroOrientation[2] + 2.0 * Math.PI) + oneMinusCoeff * accMagOrientation[2]);
fusedOrientation[2] -= (fusedOrientation[2] > Math.PI) ? 2.0 * Math.PI : 0;
}
else if (accMagOrientation[2] < -0.5 * Math.PI && gyroOrientation[2] > 0.0) {
fusedOrientation[2] = (float) (FILTER_COEFFICIENT * gyroOrientation[2] + oneMinusCoeff * (accMagOrientation[2] + 2.0 * Math.PI));
fusedOrientation[2] -= (fusedOrientation[2] > Math.PI)? 2.0 * Math.PI : 0;
}
else {
fusedOrientation[2] = FILTER_COEFFICIENT * gyroOrientation[2] + oneMinusCoeff * accMagOrientation[2];
}
// overwrite gyro matrix and orientation with fused orientation
// to comensate gyro drift
gyroMatrix = getRotationMatrixFromOrientation(fusedOrientation);
System.arraycopy(fusedOrientation, 0, gyroOrientation, 0, 3);
// update sensor output in GUI
mHandler.post(updateOreintationDisplayTask);
}
}
// **************************** GUI FUNCTIONS *********************************
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch(checkedId) {
case R.id.radio0:
radioSelection = 0;
break;
case R.id.radio1:
radioSelection = 1;
break;
case R.id.radio2:
radioSelection = 2;
break;
}
}
public void updateOreintationDisplay() {
switch(radioSelection) {
case 0:
mAzimuthView.setText(d.format(accMagOrientation[0] * 180/Math.PI) + '?');
mPitchView.setText(d.format(accMagOrientation[1] * 180/Math.PI) + '?');
mRollView.setText(d.format(accMagOrientation[2] * 180/Math.PI) + '?');
try {
writeToCsv((d.format(accMagOrientation[0] * 180/Math.PI) + '?'),(d.format(accMagOrientation[1] * 180/Math.PI)+ '?'),(d.format(accMagOrientation[2] * 180/Math.PI) + '?'));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
case 1:
mAzimuthView.setText(d.format(gyroOrientation[0] * 180/Math.PI) + '?');
mPitchView.setText(d.format(gyroOrientation[1] * 180/Math.PI) + '?');
mRollView.setText(d.format(gyroOrientation[2] * 180/Math.PI) + '?');
try {
writeToCsv((d.format(gyroOrientation[0] * 180/Math.PI) + '?'),(d.format(gyroOrientation[1] * 180/Math.PI)+ '?'),(d.format(gyroOrientation[2] * 180/Math.PI) + '?'));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
case 2:
mAzimuthView.setText(d.format(fusedOrientation[0] * 180/Math.PI) + '?');
mPitchView.setText(d.format(fusedOrientation[1] * 180/Math.PI) + '?');
mRollView.setText(d.format(fusedOrientation[2] * 180/Math.PI) + '?');
try {
writeToCsv((d.format(fusedOrientation[0] * 180/Math.PI) + '?'),(d.format(fusedOrientation[1] * 180/Math.PI) + '?'),(d.format(fusedOrientation[2] * 180/Math.PI) + '?'));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
}
}
private void writeToCsv(String x, String y, String z) throws IOException {
Calendar c = Calendar.getInstance();
// File path = getFilesDir();
File folder = new File(getFilesDir() + "/TollCulator");
boolean success = true;
if (! folder.exists()) {
success = folder.mkdir();
}
if (success) {
// Do something on success
String csv = "data.csv";
FileWriter file_writer = new FileWriter(csv,true);
String s= c.get(Calendar.YEAR)+","+c.get(Calendar.MONTH)+","+c.get(Calendar.DATE)+","+c.get(Calendar.HOUR)+","+c.get(Calendar.MINUTE)+","+c.get(Calendar.SECOND)+","+ c.get(Calendar.MILLISECOND)+","+x + ","+y+","+z+"\n";
file_writer.append(s);
file_writer.close();
}
}
private Runnable updateOreintationDisplayTask = new Runnable() {
public void run() {
updateOreintationDisplay();
}
};
}
Try with below code to create csv file and save data into csv.
Reference : https://sourceforge.net/projects/opencsv/files/opencsv/
For more : Look into this
String csv = (Environment.getExternalStorageDirectory().getAbsolutePath() + "/MyCsvFile.csv"); // Here csv file name is MyCsvFile.csv
//by Hiting button csv will create inside phone storage.
buttonAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CSVWriter writer = null;
try {
writer = new CSVWriter(new FileWriter(csv));
List<String[]> data = new ArrayList<String[]>();
data.add(new String[]{"Country", "Capital"});
data.add(new String[]{"India", "New Delhi"});
data.add(new String[]{"United States", "Washington D.C"});
data.add(new String[]{"Germany", "Berlin"});
writer.writeAll(data); // data is adding to csv
writer.close();
callRead();
} catch (IOException e) {
e.printStackTrace();
}
}
});
I am developing an Augmented reality application with Rajawali lib. My problem is as below.
I want to draw a surface onto the camera view, when i tried the latest ver of rajawali, it didn't work. I spent many days and find out that the latest did not support draw over camera any more. And the rajawali v0.9 work fine. So the following question is apply for v0.9.
When i tried to register SensorEventListener, and in onSensorChanged() I got 3 values which represent 3 dimension of android device, but it was very noise and unstable. I have tried implement low-pass filter but it still noise.
Finally i found this question, but on v0.9, the
getCamera().setOrientation(quaternion)
did not work. I dont know why.
Now i don't know what to do next :(
Here is my codes, it works very well in my project, and I hope it to help you.
// The code snippet of my renderer class
#Override
public void onRender(final long elapsedTime, final double deltaTime) {
mHeadTracker.getLastHeadView(mHeadTransform.getHeadView(), 0);
android.opengl.Matrix.invertM(mHeadTransform.getHeadView(), 0, mHeadTransform.getHeadView(), 0);
Quaternion q = mHeadTransform.getQuaternion(mHeadTransform.getHeadView(), 0);
getCurrentCamera().setOrientation(q);
super.onRender(elapsedTime, deltaTime);
}
// The code snippet of HeadTransform class
private static Quaternion sQuaternion = new Quaternion();
public Quaternion getQuaternion(float[] quaternion, int offset) {
if (offset + 4 > quaternion.length) {
throw new IllegalArgumentException(
"Not enough space to write the result");
}
float[] m = this.mHeadView;
float t = m[0] + m[5] + m[10];
float x;
float y;
float z;
float w;
float s;
if (t >= 0.0F) {
s = (float) Math.sqrt(t + 1.0F);
w = 0.5F * s;
s = 0.5F / s;
x = (m[9] - m[6]) * s;
y = (m[2] - m[8]) * s;
z = (m[4] - m[1]) * s;
} else {
if ((m[0] > m[5]) && (m[0] > m[10])) {
s = (float) Math.sqrt(1.0F + m[0] - m[5] - m[10]);
x = s * 0.5F;
s = 0.5F / s;
y = (m[4] + m[1]) * s;
z = (m[2] + m[8]) * s;
w = (m[9] - m[6]) * s;
} else {
if (m[5] > m[10]) {
s = (float) Math.sqrt(1.0F + m[5] - m[0] - m[10]);
y = s * 0.5F;
s = 0.5F / s;
x = (m[4] + m[1]) * s;
z = (m[9] + m[6]) * s;
w = (m[2] - m[8]) * s;
} else {
s = (float) Math.sqrt(1.0F + m[10] - m[0] - m[5]);
z = s * 0.5F;
s = 0.5F / s;
x = (m[2] + m[8]) * s;
y = (m[9] + m[6]) * s;
w = (m[4] - m[1]) * s;
}
}
}
quaternion[(offset + 0)] = x;
quaternion[(offset + 1)] = y;
quaternion[(offset + 2)] = z;
quaternion[(offset + 3)] = w;
Log.d("facevr", x + "," + y + "," + z + "," + w);
return sQuaternion.setAll(w, x, y, z);
}
I am getting the accelerometer values continuously (i.e) X and Y values in the run time. My question is that when the values of the accelerometer changes in mobile the corresponding values should be accumulated as per the change.
This is my code :
public class MainActivity extends Activity implements SensorEventListener {
private SensorManager sensorManager;
private float accumulation_x = 0;
private float accumulation_y = 0;
private float accumulation_z = 0;
private TextView acessTextview, angleTextview;
private float value;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById();
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
sensorManager.registerListener(this,
sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_NORMAL);
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
int count = 1;
while(count!=0){
float x = (float) 0.9887777;
float y = (float) 0.187359372;
float z = (float) 0.0228636;
float X_axis = (float) (x + (0.02724095));
float Y_axis = (float) (y + (-0.027792556));
float Z_axis = (float) (z - (0.105689));
accumulation_x = accumulation_x + X_axis;
accumulation_y = accumulation_y + Y_axis;
accumulation_z = accumulation_z + Z_axis;
value = (y / z);
float angle = (float) Math.toDegrees(Math.atan(value));
angleTextview.setText("Angle:" + angle);
acessTextview.setText("accumulation_x :" + X_axis + "\n"
+ "accumulation_y :" + Y_axis + "\n"
+ "accumulation_z :" + Z_axis);
count++;
}
}
}
private void findViewById() {
// TODO Auto-generated method stub
acessTextview = (TextView) findViewById(R.id.accessTextview);
angleTextview = (TextView) findViewById(R.id.angleTextview);
}
}
Your code is correct, only minor changes are require, I have updated your code with an extra method called refreshValues(). This method will set the latest values of X,Y in to TextView. This method will get called from onSensorChanged() method.
public class MainActivity extends Activity implements SensorEventListener {
private SensorManager sensorManager;
private float accumulation_x = 0;
private float accumulation_y = 0;
private float accumulation_z = 0;
private TextView acessTextview, angleTextview;
private float value;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById();
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
sensorManager.registerListener(this,
sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_NORMAL);
}
public void onAccuracyChanged(Sensor sensor, int accuracy) { }
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
int count = 1;
while(count!=0){
float x = (float) 0.9887777;
float y = (float) 0.187359372;
float z = (float) 0.0228636;
float X_axis = (float) (x + (0.02724095));
float Y_axis = (float) (y + (-0.027792556));
float Z_axis = (float) (z - (0.105689));
accumulation_x = accumulation_x + X_axis;
accumulation_y = accumulation_y + Y_axis;
accumulation_z = accumulation_z + Z_axis;
value = (y / z);
float angle = (float) Math.toDegrees(Math.atan(value));
angleTextview.setText("Angle:" + angle);
acessTextview.setText("accumulation_x :" + X_axis + "\n"
+ "accumulation_y :" + Y_axis + "\n"
+ "accumulation_z :" + Z_axis);
count++;
}
}
refreshValues ( accumulation_x,accumulation_y );
}
private void findViewById() {
// TODO Auto-generated method stub
acessTextview = (TextView) findViewById(R.id.accessTextview);
angleTextview = (TextView) findViewById(R.id.angleTextview);
}
private void refreshValues ( float x, float y )
{
acessTextview.setText ( String.valueOf(x) );
angleTextview.setText( ( String.valueOf(y)));
}
}
How can we convert an Int value to an angle.
int speed = remoteService.getSpeed();
I am getting the speed value from a remote service and I want to convert it to an angle.
How can I do this? Any Idea?
public void getGenginePos(int state,float force, double AOD){
double AODrad=(AOD*0.017444);
switch(state){
case BOAT_IDLE:
//System.out.println("Before Vx = " + vx + ", vy = " + vy + ", f = " + force + ", AOD = " + AOD);
vx = (float)(force * Math.cos(AODrad));
px = px + (vx * dt);
vy = (float) (force * Math.sin(AODrad));
//System.out.println("After Vx = " + vx + ", vy = " + vy);
py = py - (vy * dt);
break;
case BOAT_ACCEL:
temp = force *dt;
vx = (float) (force * Math.cos(AODrad) + temp);//(force * dt));
vy = (float) (force * Math.sin(AODrad) + temp);//(force * dt));
px = px + (vx * dt);
py = py - (vy * dt);
break;
case BOAT_DECEL:
temp = force *dt;
vx = (float) (force * Math.cos(AODrad) - temp);//(force * dt));
vy = (float) (force * Math.sin(AODrad) - temp);//(force * dt));
px = px + (vx * dt);
py = py - (vy * dt);
break;
default: break;
}
}
public void setMeterPos(int rpx,int rpy,int epx,int epy){
RefX= rpx;
RefY= rpy;
EndX = epx;
EndY = epy;
screenwidth=BoatRider.screenWidth;
screenheight=BoatRider.screenHeight;
}
public void setArrowEndX(int x){
EndX = x;
}
public void setArrowEndY(int y){
EndY = y;
}
public float getArrowEndX(){
return EndX;
}
public float getArrowEndY(){
return EndY;
}
public void getGMeterArrowPos(double AOD,float radius){
double AODrad=(AOD*0.017444);
vx=(float)(radius*Math.cos(AODrad));
vy=(float)(radius*Math.sin(AODrad));
float height=screenheight-RefY;
EndX = vx+RefX;
EndY=screenheight-(vy+height);
}
public float getBorderEndX(){
return EndX;
}
public float getBorderEndY(){
return EndY;
}
public void getGBoatBorderPos(double AOD,float radius,float boderRefX,float boderRefY){
double AODrad=(AOD*0.017444);
vx=(float)(radius*Math.cos(AODrad));
vy=(float)(radius*Math.sin(AODrad));
float height=screenheight-boderRefY;
EndX = vx+boderRefX;
EndY=screenheight-(vy+height);
}
}
it will be very useful
int speed = 90;
double degrees = speed ;
double angle = degrees * 2 * Math.PI / 360.0;
Or you can use
int speed = 30;
double degrees = speed;
double toDegree = Math.toDegrees(radians);