Interpreting Sensor Readings

The sensor service will call your onSensorChanged() method every time a value changes. It should look something like this:

4. Unfortunately, Android 1.5 removed support for the TRICORDER sensor that turned your device into a fully functional Star Trek tricorder. Darn it, Jim—I'm a programmer, not an ovum paschalis.

Download SensorTest/src/org/example/sensortest/SensorTest.java

public void onSensorChanged(SensorEvent event) {

for (int i = 0; i < event.values.length; i++) { // ...

All the sensors return an array of floating-point values. The size of the array depends on the particular sensor; for example, TYPE_ TEMPERATURE returns only one value, the temperature in degrees Celsius. You may not even need to use all the numbers returned. For instance, if you just need a compass heading, you can use the first number returned from the TYPE_ORIENTATION sensor.

Turning the sensor readings (especially from the accelerometer) into meaningful information is something of a black art. Here are a few tips to keep in mind:

• Accelerometer readings are extremely jittery. You'll need to smooth out the data using some kind of weighted averaging, but you have to be careful not to smooth it too much, or your interface will feel laggy and soft.

• Sensor numbers will come in at random times. You may get several in a row, then have a short pause, and then receive a bunch more. Don't assume a nice even rate.

• Try to get ahead of the user by predicting what they're going to do next. Let's say the last three readings show the start of a roll to the right, with each one a little faster than the last. You can guess with some degree of accuracy what the next reading is going to be and start reacting based on your prediction.

The most challenging use of sensors is an action game that requires a one-to-one connection between how the player moves the device and what happens on the screen. Unfortunately, the emulator isn't going to be much use for this kind of thing.

0 0

Post a comment