webOS Development: AccelBall – A Practical Accelerometer Demo
Not too long back, Marta upgraded her phone and snagged a Palm Pre. Of course, this meant that I would immediately begin obsessing over developing apps for the Palm Pre. Since this bad boy of a device runs its own Linux variant, there’s plenty to hack around on “under the hood” as well. I’m now fairly comfortable with the webOS APIs and will soon embark on developing some useful apps. Along the way, I’ll be sure to document some of what I learn about this amazing device.
In the mean time, I recently posted an accelerometer demo and its code over on PreCentral’s webOS Development forums. Figured I would toss it up here on the ‘ole blog as well.
Who Knows How to Use the Accelerometer?
On the development forums, there has been a lot of interest in writing apps which use the accelerometer, but not much code to get anyone started. My goal was purely to give the Palm Pre development community some code to chew on, so this is about as basic as it gets. AccelBall just lets you hold your Pre flat and tip it back and forth to roll a ball around. That’s it. That’s all. Figured it would be something fun to play around with for coders new to the Pre.
Making Things Move
I’ll assume anyone reading this will already know the basics of how to get a webOS app started, so this is just the code that is relevant to doing something useful with the Pre’s raw accelerometer data. Just one event handler and a tiny bit of math pulls off the heavy lifting:
MainAssistant.prototype.handleAcceleration = function(event) {
this.driftX += (event.accelX * this.scale);
this.driftY += (event.accelY * this.scale);
this.driftZ += (event.accelZ * this.scale);
}
And a PeriodicalExecuter to move the ball around once every 30th of a second:
MainAssistant.prototype.setup = function() {
...
new PeriodicalExecuter(function(pe) {
obj.moveDot();
}, (1/30));
...
}
The moveDot function just uses the drift variables which are being updated by the accelerometer’s event handler:
MainAssistant.prototype.moveDot = function(){
// Move that dot! Note that the Z axis isn't used in this demo...
this.theDot.style.left = (parseInt(this.theDot.style.left) + this.driftX) + 'px';
this.theDot.style.top = (parseInt(this.theDot.style.top) - this.driftY) + 'px';
// And there's more code to keep the ball within the viewport, just snag the source...
}
The Code and IPK
To make life easier, here’s a zip of the complete source of AccelBall, ready to be used with ‘palm-package’ out of the box. Also, the all-important IPK package for those who just want to install and toy with it.
Code: accelball-source.zip
IPK: com.randallagordon.accelball_0.0.0_all.ipk
And last, but not least, I’ll include a link to the official Palm documentation on the Accelerometer’s API for good measure.
I hope you find the code useful and if you make anything with it, please leave a comment and a link. I would love to see what creative applications everyone comes up with!



