Accessing the Accelerometer

Tutorials with advanced 'difficulty' and more Lines of Code.

Accessing the Accelerometer

Postby plusminus » Fri Jan 11, 2008 8:27 pm

Accessing the Accelerometer


What is this: Your will learn how to access the Accelerometer

:warning: Currently the emulator does not support the emulation of an accelerometer (it just returns [0, 0, 0] what is a Free-Fall ;)). But when the functionality is available I will build a Class, where you can register, for special events, like, when the device is being shaken or similar.

:?: Problems/Questions: post right below...

Difficulty: 2 of 5

Description: The accelerometer values indicate the acceleration in units of 1 = 1g = 9.8 m/s[sup]2[/sup] along the X, Y, and Z axes. With the device lying flat on a horizontal surface in front of the user, oriented so the screen is readable by the user in the normal fashion, the X axis goes from left to right, the Y axis goes from the user toward the device, and the Z axis goes upwards perpendicular to the surface.

Acceleration is defined such that a device in free fall has an accleration value of (0, 0, 0). Thus a stationary device will have an acceleration value of (0, 0, -1) since it is being acted on with 1g of force by the Earth's gravity. When the device is stationary, the acceleration vector will thus indicate the downward direction.

0.) So I created a small wrapper around the basic-functionality of Sensor-Reading, that will save you some lines:

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. import android.hardware.Sensors;
  2.  
  3. public class AccelerometerReader {
  4.  
  5.         /** True when the Accelerometer-functionality is basically available. */
  6.         boolean accelerometerAvailable = false;
  7.         boolean isEnabled = false;
Parsed in 0.031 seconds, using GeSHi 1.0.8.4


1.) Constructing a AccelerometerReader which does some initial work:
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.         /**
  2.          * Sets up an AccelerometerReader. Checks if Accelerometer is available on
  3.          * this device and throws UnsupportedOperationException if not .
  4.          *
  5.          * @param doEnable :
  6.          *            enables the devices Accelerometer
  7.          *            initially (if sensor available)
  8.          * @throws UnsupportedOperationException
  9.          *             if Accelerometer is not available on this device.
  10.          */
  11.         public AccelerometerReader(boolean doEnable)
  12.                         throws UnsupportedOperationException {
  13.  
  14.                 /* Check once here in the constructor if an
  15.                  * Accelerometer is available on this device. */
  16.                 for (String aSensor : Sensors.getSupportedSensors())
  17.                         if (aSensor.equals(Sensors.SENSOR_ACCELEROMETER))
  18.                                 accelerometerAvailable = true;
  19.  
  20.                 if (!accelerometerAvailable)
  21.                         throw new UnsupportedOperationException(
  22.                                         "Accelerometer is not available.");
  23.  
  24.                 if (doEnable)
  25.                         setEnableAccelerometer(true);
  26.         }
Parsed in 0.032 seconds, using GeSHi 1.0.8.4


2.) Dis/Enabling of the underlying Accelerometer:
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.         /**
  2.          * En/Dis-able the Accelerometer.
  3.          *
  4.          * @param doEnable
  5.          *            <code>true</code> for enable.<br>
  6.          *            <code>false</code> for disable.
  7.          * @throws UnsupportedOperationException
  8.          */
  9.         public void setEnableAccelerometer(boolean doEnable)
  10.                         throws UnsupportedOperationException {
  11.                 if (!accelerometerAvailable)
  12.                         throw new UnsupportedOperationException(
  13.                                         "Accelerometer is not available.");
  14.  
  15.                 /* If should be enabled and not already is: */
  16.                 if (doEnable && !this.isEnabled) {
  17.                         Sensors.enableSensor(Sensors.SENSOR_ACCELEROMETER);
  18.                         this.isEnabled = true;
  19.                 } else /* If should be disabled and not already is: */
  20.                 if (!doEnable && this.isEnabled) {
  21.                         Sensors.disableSensor(Sensors.SENSOR_ACCELEROMETER);
  22.                         this.isEnabled = false;
  23.                 }
  24.         }
Parsed in 0.037 seconds, using GeSHi 1.0.8.4


3.) Readign out the actual values:
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.         /**
  2.          * Read out the values currently provided by the Accelerometer.
  3.          *
  4.          * @return the current Accelerometer-values.
  5.          * @throws UnsupportedOperationException
  6.          *             if Accelerometer is not available on this device.
  7.          * @throws IllegalStateException
  8.          *             if Accelerometer was set to disabled.
  9.          */
  10.         public float[] readAccelerometer() throws UnsupportedOperationException, IllegalStateException {
  11.                 if (!accelerometerAvailable)
  12.                         throw new UnsupportedOperationException(
  13.                                         "Accelerometer is not available.");
  14.  
  15.                 if (!this.isEnabled)
  16.                         throw new IllegalStateException(
  17.                                         "Accelerometer was set to disabled!");
  18.                 /* Get number of sensor-values the sensor will return. Could be
  19.                  * variable, depending of the amount of axis (1D, 2D or 3D
  20.                  * accelerometer). */
  21.                 int sensorValues = Sensors
  22.                                 .getNumSensorValues(Sensors.SENSOR_ACCELEROMETER);
  23.                 float[] out = new float[sensorValues];
  24.  
  25.                 /* Make the OS fill the array we passed. */
  26.                 Sensors.readSensor(Sensors.SENSOR_ACCELEROMETER, out);
  27.  
  28.                 /* And return it. */
  29.                 return out;
  30.         }
  31. }
Parsed in 0.038 seconds, using GeSHi 1.0.8.4

Thats it :)


The full source:

"/src/your_package_structure/AccelerometerReader.java"
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. package org.anddev.dummyproject;
  2.  
  3. import android.hardware.Sensors;
  4.  
  5. public class AccelerometerReader {
  6.  
  7.         /** True when the Accelerometer-functionality is basically available. */
  8.         boolean accelerometerAvailable = false;
  9.         boolean isEnabled = false;
  10.  
  11.         /**
  12.          * Sets up an AccelerometerReader. Checks if Accelerometer is available on
  13.          * this device and throws UnsupportedOperationException if not .
  14.          *
  15.          * @param doEnable :
  16.          *            enables the devices Accelerometer
  17.          *            initially (if sensor available)
  18.          * @throws UnsupportedOperationException
  19.          *             if Accelerometer is not available on this device.
  20.          */
  21.         public AccelerometerReader(boolean doEnable)
  22.                         throws UnsupportedOperationException {
  23.  
  24.                 /* Check once here in the constructor if an
  25.                  * Accelerometer is available on this device. */
  26.                 for (String aSensor : Sensors.getSupportedSensors())
  27.                         if (aSensor.equals(Sensors.SENSOR_ACCELEROMETER))
  28.                                 accelerometerAvailable = true;
  29.  
  30.                 if (!accelerometerAvailable)
  31.                         throw new UnsupportedOperationException(
  32.                                         "Accelerometer is not available.");
  33.  
  34.                 if (doEnable)
  35.                         setEnableAccelerometer(true);
  36.         }
  37.  
  38.         /**
  39.          * En/Dis-able the Accelerometer.
  40.          *
  41.          * @param doEnable
  42.          *            <code>true</code> for enable.<br>
  43.          *            <code>false</code> for disable.
  44.          * @throws UnsupportedOperationException
  45.          */
  46.         public void setEnableAccelerometer(boolean doEnable)
  47.                         throws UnsupportedOperationException {
  48.                 if (!accelerometerAvailable)
  49.                         throw new UnsupportedOperationException(
  50.                                         "Accelerometer is not available.");
  51.  
  52.                 /* If should be enabled and not already is: */
  53.                 if (doEnable && !this.isEnabled) {
  54.                         Sensors.enableSensor(Sensors.SENSOR_ACCELEROMETER);
  55.                         this.isEnabled = true;
  56.                 } else /* If should be disabled and not already is: */
  57.                 if (!doEnable && this.isEnabled) {
  58.                         Sensors.disableSensor(Sensors.SENSOR_ACCELEROMETER);
  59.                         this.isEnabled = false;
  60.                 }
  61.         }
  62.  
  63.         /**
  64.          * Read out the values currently provided by the Accelerometer.
  65.          *
  66.          * @return the current Accelerometer-values.
  67.          * @throws UnsupportedOperationException
  68.          *             if Accelerometer is not available on this device.
  69.          * @throws IllegalStateException
  70.          *             if Accelerometer was set to disabled.
  71.          */
  72.         public float[] readAccelerometer() throws UnsupportedOperationException, IllegalStateException {
  73.                 if (!accelerometerAvailable)
  74.                         throw new UnsupportedOperationException(
  75.                                         "Accelerometer is not available.");
  76.  
  77.                 if (!this.isEnabled)
  78.                         throw new IllegalStateException(
  79.                                         "Accelerometer was set to disabled!");
  80.                 /* Get number of sensor-values the sensor will return. Could be
  81.                  * variable, depending of the amount of axis (1D, 2D or 3D
  82.                  * accelerometer). */
  83.                 int sensorValues = Sensors
  84.                                 .getNumSensorValues(Sensors.SENSOR_ACCELEROMETER);
  85.                 float[] out = new float[sensorValues];
  86.  
  87.                 /* Make the OS fill the array we passed. */
  88.                 Sensors.readSensor(Sensors.SENSOR_ACCELEROMETER, out);
  89.  
  90.                 /* And return it. */
  91.                 return out;
  92.         }
  93. }
Parsed in 0.044 seconds, using GeSHi 1.0.8.4


Regards,
plusminus
Image
Image | Android Development Community / Tutorials
User avatar
plusminus
Site Admin
Site Admin
 
Posts: 2688
Joined: Wed Nov 14, 2007 8:37 pm
Location: Schriesheim, Germany

Top

Postby nico » Thu Jan 24, 2008 5:37 am

hi, plusminus

could u provide a simple application that use your AccelerometerReader, such as change a text in TextView when the phone is shaked. or is it not possible with the current emulator?

thanks :wink:
nico
Junior Developer
Junior Developer
 
Posts: 19
Joined: Tue Nov 27, 2007 10:33 am
Location: Indonesia

Postby plusminus » Thu Jan 24, 2008 10:33 am

Hello nico,

currently there is no emulation for an accelerometer.

Regards,
plusminus
Image
Image | Android Development Community / Tutorials
User avatar
plusminus
Site Admin
Site Admin
 
Posts: 2688
Joined: Wed Nov 14, 2007 8:37 pm
Location: Schriesheim, Germany

Postby Peli » Mon Jan 28, 2008 3:52 pm

Hi!

OpenIntents has now the brand-new SensorSimulator! Now you can easily test your accelerometer-based application:

Try it out online here:
http://www.openintents.org/sensorsimulator

More information can be found here:
http://code.google.com/p/openintents/wi ... rSimulator

The phone is no longer freely falling, with the boring acceleration=(0,0,0), but you can receive real-time sensor data just by dragging around the simulated phone with the mouse.

Peli

PS: PlusMinus, you should probably change the following line in your code above:
if (aSensor.equals(Sensors.SENSOR_ACCELEROMETER))
to
if (aSensor.contentEquals(Sensors.SENSOR_ACCELEROMETER))
since the former version will compare pointer addresses, but the latter version compares strings. (just in case there are two equal strings, but with different address...)
Peli
Junior Developer
Junior Developer
 
Posts: 17
Joined: Thu Dec 27, 2007 10:54 am

Postby Peli » Mon Jan 28, 2008 3:54 pm

PlusMinus,

By the way, I used your pyramid for the OpenGLSensors demo :-) I hope that is ok, and I don't violate any copyright :-)

Peli
Peli
Junior Developer
Junior Developer
 
Posts: 17
Joined: Thu Dec 27, 2007 10:54 am

Postby plusminus » Tue Jan 29, 2008 1:36 am

Hello Peli,

nice to see the code reused. :)

Actually I'm pretty sure, that .equals also does a Content-Check for Equality.
Comparing by "==" would do a Pointer(Reference)-Comparison.

Regards,
plusminus
Image
Image | Android Development Community / Tutorials
User avatar
plusminus
Site Admin
Site Admin
 
Posts: 2688
Joined: Wed Nov 14, 2007 8:37 pm
Location: Schriesheim, Germany

Top

Hi

Postby nit1507 » Tue Jan 29, 2008 4:22 pm

Thanks Peli for this wonderful SensorSimulator! . Also Thanks to plusminus for showing wonderful code.


Regrds

nit1507
User avatar
nit1507
Freshman
Freshman
 
Posts: 6
Joined: Wed Jan 09, 2008 4:27 pm
Location: Chennai, India

Postby Peli » Wed Jan 30, 2008 7:20 am

plusminus wrote:Actually I'm pretty sure, that .equals also does a Content-Check for Equality.
Comparing by "==" would do a Pointer(Reference)-Comparison.


I guess you are right. I must have done something stupid :roll: , like comparing a string to a CharSequence (if that is a test that fails...). In any case, I had some trouble some days ago and that got resolved by changing equals to contentEquals, but reading through the documentation, I agree with you that equals should already compare the strings, so probably my mistake was somewhere else and I had not noticed it...

nit1507, thanks for the positive feedback :-)

Peli
Peli
Junior Developer
Junior Developer
 
Posts: 17
Joined: Thu Dec 27, 2007 10:54 am

Postby plusminus » Wed Jan 30, 2008 10:45 am

Hello peli,

java.lang.String implements the CharSeqeunce-Interface, so the following code is correct:
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.                 String s = "hello";
  2.                 CharSequence cs = "hello";
  3.                
  4.                 boolean b = s.equals(cs); // b will be 'true'
Parsed in 0.037 seconds, using GeSHi 1.0.8.4


Regards,
plusminus
Image
Image | Android Development Community / Tutorials
User avatar
plusminus
Site Admin
Site Admin
 
Posts: 2688
Joined: Wed Nov 14, 2007 8:37 pm
Location: Schriesheim, Germany

Application error: org.anddev.dummyproject

Postby parashar.iiit » Sat Feb 02, 2008 12:58 pm

Hello i am getting an error while starting the application -

"An error has occurred in process org.anddev.dummyproject . Unable to instantiate activity ."

Can somebody tell me why has this problem occurred ??

Thanks in advance
Abhinav
User avatar
parashar.iiit
Junior Developer
Junior Developer
 
Posts: 10
Joined: Sat Feb 02, 2008 12:51 pm

Postby plusminus » Sat Feb 02, 2008 1:27 pm

Hello parashar.iiit,

is there no further detail to the Exception :?:

Just tried my code again and it worked fine.
Perhaps provide some code (if you are sure it has sth. to do with my Accelerometer-Reader here, otherwise in a new topic) :?:

Regards,
plusminus
Image
Image | Android Development Community / Tutorials
User avatar
plusminus
Site Admin
Site Admin
 
Posts: 2688
Joined: Wed Nov 14, 2007 8:37 pm
Location: Schriesheim, Germany

Postby parashar.iiit » Sat Feb 02, 2008 1:55 pm

Hello plusminus,
Thanks for your reply. Actually first time i am facing this error .I also just tried the code again but the same error is coming again .

An error has occured in process org.anddev.dummyproject. Unable to
instantiate activity
ComponentInfo{org.anddev.dummyproject.AccelerometerReader};
java.lang.InstantiationException:
org/anddev/dummyproject/AccelerometerReader


I guess now you can understand my problem .

Thanks
User avatar
parashar.iiit
Junior Developer
Junior Developer
 
Posts: 10
Joined: Sat Feb 02, 2008 12:51 pm

Postby plusminus » Sat Feb 02, 2008 2:31 pm

Hello parashar.iiit,

the code above is no Activity :!: it just a normal Java-Class you use.
i.e. you'll have it as a field in your Activity:
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. public class TestLayout extends Activity {
  2.  
  3.        
  4.  
  5.         private AccelerometerReader myAcReader = new AccelerometerReader(true);
  6.  
  7.  
  8.  
  9.         @Override
  10.  
  11.         public void onCreate(Bundle icicle) {
  12.  
  13.                 super.onCreate(icicle);
  14.  
  15.                 this.setContentView(R.layout.main);
  16.  
  17.                 // Perhaps make a button-OnClick show the Accelerometer-Values in a TextView...
  18.  
  19.         }
  20.  
  21. }
Parsed in 0.037 seconds, using GeSHi 1.0.8.4


Did this help you :?:
If not please provide the Activity where you are using the AccelerometerReader. :)

Regards,
plusminus
Image
Image | Android Development Community / Tutorials
User avatar
plusminus
Site Admin
Site Admin
 
Posts: 2688
Joined: Wed Nov 14, 2007 8:37 pm
Location: Schriesheim, Germany

Postby parashar.iiit » Sat Feb 02, 2008 3:08 pm

Oh thanks pulsminus .... Its working ....Such a stupid mistake i was making ... :(
User avatar
parashar.iiit
Junior Developer
Junior Developer
 
Posts: 10
Joined: Sat Feb 02, 2008 12:51 pm

Postby plusminus » Sat Feb 02, 2008 3:11 pm

parashar.iiit wrote:Oh thanks pulsminus .... Its working ....Such a stupid mistake i was making ... :(


^^ Everyone makes such a fault somewhen :roll:
Image
Image | Android Development Community / Tutorials
User avatar
plusminus
Site Admin
Site Admin
 
Posts: 2688
Joined: Wed Nov 14, 2007 8:37 pm
Location: Schriesheim, Germany

Top
Next

Return to Advanced Tutorials

Who is online

Users browsing this forum: No registered users and 3 guests