Skip to content

Using sensors

The Android sensor framework (ASF) already does a good job of providing a generic abstract interface for the sensors on board a mobile device. Processing makes use of the ASF and provides some additional streamlining. For this reason, you need to know a little about the ASF to fully understand what the Processing code is doing. You can use the first link in the resources box to find an overview.

Once you know about sensor managers, sensor events and sensor event listeners, go on to the Processing sensor tutorial using the second resources link. There you will learn how to create a simple app which displays the readings from the accelerometer. Note that there is an error in the final example which makes use of the Box2D library, and you should therefore not try to use it.

Extra challenge

Once you have the example application working, you can combine it with the example from the Getting Started tutorial to create a simple game. Modify the code to make the following changes:

  • Work out the values that should be shown in the x, y and z directions to indicate that the device is being held at 45°

  • Decide on a minimum and maximum threshold value in each direction

  • Change the background colour to red when the accelerometer values go outside these thresholds

  • Optionally add an alarm sound to accompany the colour change

The game consists of trying to carry the device from a starting point to a target point while keeping it at the correct angle. If you are playing with other people, the winner would be the first person who makes it to the target point without triggering the alarm. If a person triggers the alarm, they have to return to the start. You can make the game more difficult either by tightening the thresholds, or by choosing a target point that is more difficult to get to - round corners, up stairs, etc.

Further reading

Android sensors

Android mode