The accelerometer measures force in either a positive or negative direction with respect to an axis of direction. Negative G's in a direction are will result in a value less than 511/512, positive G's will be greater than 511/512. Tipping the device can result in positive or negative force with respect to a particular axis.
The Pac-Man character can move in one of 4 directions. To determine which of those directions to move the axis which is exhibiting the greatest displacement from center must first be found, then the direction of that displacement is then considered to come up with a direction that Pac-Man is to be directed to move to.
After the voltage is accurately measured in both directions the following code could be used to determine which direction the user wishes to move Pac-Man, or no direction at all if the device was held at a position close to rest.
// enumerate directions
up = 0,
right = 1,
down = 2,
left = 3,
none = 4
// The direction of force in relation to axis.
negative = 0,
positive = 1
// A value which magnitude must be above to register movement.
const short kThreshHold = 5;
unsigned char AccelDirection( short xVal, short yVal)
short xMag = xVal - 512;
short yMag = yVal - 512;
unsigned char xDirection = positive;
unsigned char yDirection = positive;
if (xMag < 0)
xMag = xMag * -1;
xDirection = negative;
if (yMag < 0)
yMag = yMag * -1;
yDirection = negative;
if (xMag - kThreshHold > 0 && xMag > yMag)
if (xDirection == negative )
else if (yMag -kThreshHold > 0 && yMag > xMag)
if (yDirection == negative )