Your iPhone has a number of sensors, some of which are rather essential for the phone’s operation (such as the microphone). While the accelerometer and the gyroscope might not be the most essential sensors for a phone, they’re certainly the most exciting ones. While accelerometer measures the acceleration you induce on the phone, the gyroscope gives a rather precise feedback on the orientation of the phone.
Until now, web developers didn’t have access to the accelerometer sensor and the gyroscope sensor. With this week’s release of iOS 4.2, this has changed and we can now use DeviceMotionEvent and DeviceOrientationEvent to determine the acceleration and orientation data of the phone.
Let’s first determine whether the current browser supports device orientation sensing:
We can then read the sensor data by registering the respective callbacks. Here’s how you read the accelerometer’s data:
1 2 3 4 5 6 7 8 9 10 11
The gyroscope’s data can be read like this:
1 2 3 4 5
I’ve put together a little demo that uses the sensor data to color some boxes on the phone’s screen. Here’s a short video showing it in action:
If you want to take it for a spin, open this URL in mobile safari on your phone: http://demos.peterfriese.de/gyro/gyro.html.
(image of Gyroscope by stop that pigeon! taken from http://www.flickr.com/photos/25312309@N05/2651042796/)