Header Sep

Java Tips, Tricks & Code

My Rating Score
Login to rate page

August 2007

Utilize the W910 accelerometer in the Java ME Platform using JSR 256 - The Bouncing Ball Game

New Java Platform 8 (JP-8) phones introduce, among other things, programmatic support for sensors (JSR 256). This example shows how to utilize the built-in accelerometer in the W910 mobile phone using the sensor API. This API can, in the same manner, be used for other sensors if available.

Download example MIDlet>>

Sensors like an accelerometer can easily be incorporated into games, enriching the gaming experience on mobile phones. Information regarding available sensors can be retrieved through the use of the following API calls:

String sensorVersion = System.getProperty("microedition.sensor.version");
SensorInfo[] si = SensorManager.findSensors(null, null);

One can also specify a sensor when querying for sensor information in this call:
 
SensorInfo[] si = SensorManager.findSensors("acceleration", SensorInfo.CONTEXT_TYPE_USER);

Information contained in the sensor information array specifies exactly what type of information can be retrieved divided into different channels (in this case acceleration in three dimensions: x, y and z). The following is an example of the type of information provided by the accelerometer:

getDescription: ThreeChannelAccelerometer
getUrl: sensor:acceleration;contextType=user;model=ST_LIS302DL;location=inside
Channels:
  getName: X
  Data type: TYPE_INT
  getUnit: G
  getAccuracy: 0.0
  Measurement range:
    getSmallestValue:-2300.0
    getLargestValue: 2300.0
    getResolution: 0.015625
  getName: Y
  …
  getName: Z
  …

In order to utilize the sensor, a connection using the URL specified in the sensor information has to be opened. Once the connection is established, you can either register a data listener (a class overriding DataListener) for automatic callbacks or manually poll the sensor.

SensorConnection sensor = (SensorConnection)Connector.open(URL);
sensor.setDataListener(this, 10);

Sensors like the accelerometer above sample continuously at a fixed rate specified in the sensor information above. The accelerometer has specified a rate of 20Hz as we can see from the sensor information. Specifying the buffer size of a data listener or a "getData()" function call have the effect that the sensor will fill up as many "Data" objects as specified before calling the callback function or returning from the "getData()" function call. In our case this will result in 10 data samples for each call to our data listener, thus it is called 2 times per second (20Hz * 10 samples = 1/2 seconds).

Attached is a small example game using the accelerometer for user input. The game is a simple bouncing ball that reacts to acceleration. Please try it out for yourselves.


More information:

My Rating Score
Login to rate page