Mobile accelerometer input


Almost each mobile device has an accelerometer built in. This accelerometer measures tilt and motion. Any motion of the mobile device can be captured with javascript and html5. This values can be used to control either a mobile game or a webApp accordingly to the motion of the device. It’s really simple to read this data without any library, we just use the javascript deviceOrientation event. There are other events that are related to device motion, but the deviceOrientation event has the best cross device compatibility.

Read the W3C recommendation about all the device motion events here. There you can get all the informations you eventually need.

DeviceOrientation event

The device deviceOrientation event returns multiple values, such as gamma, beta and alpha. Each of this values represents the current position of the device itself. Once the device is in motion, the values will change accordingly. The deviceOrientation event must be applied to the window object. It might be a good idea to check first if the deviceOrientation event is available, this is done by the first line of the code. Once the device is in motion, we can catch all the values and start using them.

gamma
gamma
beta
beta
alpha
alpha

if (window.DeviceOrientationEvent) {
		
		window.addEventListener("deviceorientation", function(event) 
		{
			
			var xValue = Math.round(event.gamma);
			var yValue = Math.round(event.beta);
			var Rotation = Math.round(event.alpha);
			
		}, true);
		
		
		
	} else {
	alert("Sorry, your browser doesn't support Device Orientation");
	}

These are two simple examples for the device orientation event. The code of the demos are almost identical to the code above. It just uses the values to manipulate an object on the screen. This is a basic test of the device orientation event, it may need some additional work for better results.

Force demo

A simple visualization of the force that is applied while the mobile device is in motion.

Gyro_ballApp

Ball demo

A Ball is moving accordingly to the device motion. Stopped by the boundaries of the display.

Conclusion

This solution worked on almost every mobile device and browser i’ve tested it on. It’s easy and fast to implement. Once we get all the values, it’s possible to animate or manipulate everything accordingly to the device motion. This is basic html5 and will work in combination with all html5 based libraries.