Why do my accelerometers respond so slowly? - iphone

I'm asking them at 50Hz / 50 times per second for data. When I suddenly flip the device on the x-axis by 90 degrees while the device was flat on a table with display facing up bevore, the values move pretty slowly to the "target" value for that position.
Now the weird thing is: If I increase the measurement-rate, the value will move faster to that new value upon suddenly flipping the device by 90 degrees. But if I just ask once per second for the new value, it take's very long until the value reaches the target. What can be the reason for this?
I don't do any kind of data aggregation, and don't accumulate anything. I just do some simple filtering to get rid of the noise. My method looks like this:
- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {
// Use a basic low-pass filter to only keep the gravity in the accelerometer values for the X and Y axes
// accelerationX is an instance variable
accelerationX = acceleration.x * 0.05 + accelerationX * (1.0 - 0.05);
// round
int i = accelerationX * 100;
float clippedAccelerationValue = i;
clippedAccelerationValue /= 100;
[self moveViews:clippedAccelerationValue];
}
later on, in my -moveViews: method, I do this:
-(IBAction)moveSceneForPseudo3D:(float)accelerationValue {
if(fabs(lastAccelerationValue - accelerationValue) > 0.02) { // some little treshold to prevent flickering when it lays on a table
float viewAccelerationOffset = accelerationValue * 19 * -1;
newXPos = initialViewOrigin + viewAccelerationOffset;
myView.frame = CGRectMake(newXPos, myView.frame.origin.y, myView.frame.size.width, myView.frame.size.height);
lastAccelerationValue = accelerationValue;
}
}
As a result, of the device gets turned 90 degrees on the x-achsis, or 180 degrees, the view just moves pretty slowly to it's target position. I don't know if that's because of the physics of the accelerometers, or if it's a bug in my filtering code. I only know that there are fast paced games where the accelerometers are used for steering, so I almost can't imagine that's a hardware problem.

This line:
accelerationX = acceleration.x * 0.05 + accelerationX * (1.0 - 0.05);
is a low-pass filter, which works by computing a moving average of the x acceleration. In other words, each time that callback is called, you're only moving the accelerationX by 5% towards the new accelerometer value. That's why it takes many iterations before accelerationX reflects the new orientation.
What you should do is increase the 0.05 value, to say 0.2. I'd make a global #define and play around with different values along with different refresh rates.

Related

Calculate Jerk and Jounce from iPhone accelerometer data

I am trying to calculate Jerk (http://en.wikipedia.org/wiki/Jerk_(physics)) and jounce (http://en.wikipedia.org/wiki/Jounce) with the acceleration data from the accelerometer. I think I have Jerk figured out, but I am not sure what I am doing for jounce is correct. Can anyone confirm or deny what I am doing is giving me correct values (Do I need to take into consideration time?)
#define kFilteringFactor 0.4
float prevAccelerationX;
float prevAccelerationY;
float prevAccelerationZ;
float prevJerkX;
float prevJerkY;
float prevJerkZ;
- (void)viewDidLoad
{
[super viewDidLoad];
prevAccelerationX = 0;
prevAccelerationY = 0;
prevAccelerationZ = 0;
prevJerkX = 0;
prevJerkY = 0;
prevJerkZ = 0;
[self changeFilter:[LowpassFilter class]];
[[UIAccelerometer sharedAccelerometer] setUpdateInterval:1.0 / kUpdateFrequency];
[[UIAccelerometer sharedAccelerometer] setDelegate:self];
}
// UIAccelerometerDelegate method, called when the device accelerates.
- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration
{
float pax = prevAccelerationX;
float pay = prevAccelerationY;
float paz = prevAccelerationZ;
float pjx = prevJerkX;
float pjy = prevJerkY;
float pjz = prevJerkZ;
prevAccelerationX = acceleration.x - ( (acceleration.x * kFilteringFactor) +
(prevAccelerationX * (1.0 - kFilteringFactor)) );
prevAccelerationY = acceleration.y - ( (acceleration.y * kFilteringFactor) +
(prevAccelerationY * (1.0 - kFilteringFactor)) );
prevAccelerationZ = acceleration.z - ( (acceleration.z * kFilteringFactor) +
(prevAccelerationZ * (1.0 - kFilteringFactor)) );
// Compute the derivative (which represents change in acceleration).
float jerkX = ABS((prevAccelerationX - pax));
float jerkY = ABS((prevAccelerationY - pay));
float jerkZ = ABS((prevAccelerationZ - paz));
prevJerkX = jerkX - ( ( jerkX * kFilteringFactor) +
(prevJerkX * (1.0 - kFilteringFactor)));
prevJerkY = jerkY- ( (jerkY * kFilteringFactor) +
(prevJerkY* (1.0 - kFilteringFactor)) );
prevJerkZ = jerkZ - ( (jerkZ * kFilteringFactor) +
(prevJerkZ * (1.0 - kFilteringFactor)) );
// Compute the derivative (which represents change in acceleration).
float jounceX = ABS((prevJerkX - pjx));
float jounceY = ABS((prevJerkY - pjy));
float jounceZ = ABS((prevJerkZ - pjz));
}
In order to calculate derivatives, yes, you need to take time into consideration. Basically you can estimate jerk with just (a2-a1)/samplingtime. Its time derivative is similar. Your way of using kFilteringFactor seems weird to me but might work for your particular sampling time. You should not take ABS(), as it is perfectly valid for the derivative to be negative.
However, one big issue is probably going to be low sampling frequency. Sampling frequencies in phones are usually around 60 Hz. That means your actual bandwidth for acceleration is 30 Hz (the Nyquist frequency). Halve that and that's your jerk bandwidth. Halve that and your bandwidth for jounce, namely 7.5 Hz. Roughly speaking. All jerks (still a funny word) over 15 Hz and jounces over 7.5 Hz do not disappear but instead are aliased on top of your results. So not only you miss some information, the information you miss actually causes even more damage to your results. Properly done, you'd need low pass filtering before each derivative.
take several time series points from the acclerometer and perform B-Spline Interpolation and find the control points.
Take those points and utilize a a 3rd degree Berstein polynomial, take its first derivative and feed the control points from the B-Spline solution into the derived polynomial where t is between 0 and 1 (assuming 1 Hz sampling rate .. 0 to 1 interpolates everything in that second of time). Those values will be the Jerk/Jounce. You'll be computing this for front and side and acceleration values.

Improving Accuracy of iPhone's Accelerometer in Counting Steps

I am currently using the following code to count the number of steps a user takes in my indoor navigation application. As I am holding the phone around my chest level with the screen facing upwards, it counts the number of steps I take pretty well. But common actions like a tap on the screen or panning through the map register step counts as well. This is very frustrating as the tracking of my movement within the floor plan will become highly inaccurate. Does anyone have any idea how I can improve the accuracy of tracking in this case? Any comments will be much appreciated! To have a better idea of what I'm trying to do, you guys can check out a similar Android application at http://www.youtube.com/watch?v=wMgIa44mJXY. Thanks!
-(void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {
float xx = acceleration.x;
float yy = acceleration.y;
float zz = acceleration.z;
float dot = (px * xx) + (py * yy) + (pz * zz);
float a = ABS(sqrt(px * px + py * py + pz * pz));
float b = ABS(sqrt(xx * xx + yy * yy + zz * zz));
dot /= (a * b);
if (dot <= 0.9989) {
if (!isSleeping) {
isSleeping = YES;
[self performSelector:#selector(wakeUp) withObject:nil afterDelay:0.3];
numSteps += 1;
}
}
px = xx; py = yy; pz = zz;
}
The data from the accelerometer is basically a unidimensional (time) non uniform sampling of a three dimensional vector signal. The best way to figure out how to count steps will be to write an app that records and store the samples over a certain period of time, then export the data to a mathematical application like Wolfram's Mathematica for analysis and visualization. Remember that the sampling is non uniform, you may or may not want to transform it into a uniformly sampled digital signal.
Then you can try different signal processing algorithms to see what works best.
It's possible that, once you know the basic shape of a step in accelerometer data, you can recognize them by simple convolution.

What is happening in the following code?

This code is used in the accelerometer
method.
It uses a CGPoint variable called playerVelocity.
-(void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration
{
//controls how quickly the velocity decelerates
float deceleration = 0.4f;
//determines how sensitive the accelerometer reacts
float sensitivity = 6.0f;
//how fast the velocity can be at most
float maxVelocity = 100;
playerVelocity.x = playerVelocity.x *deceleration + acceleration.x *sensitivity;
if (playerVelocity.x < -maxVelocity)
{
playerVelocity.x = -maxVelocity;
}
else if (playerVelocity.x > maxVelocity)
{
playerVelocity.x = maxVelocity;
}
}
Now I know that the playerVelocity variable is a CGPoint so I imagine it as a X,Y Graph.
I'm assuming that wherever the playerVelocity variable is resting (let's say 150,0), it first multiplies whatever coordinates by 0.4 whenever the accelerometer input is received (which is by the iPhone being tilted)and it then add's the accelerometer.x multiplied by 6.0 to the playerVelocity variable. Is this correct?
Later on in another method, this is added to my other objects position via
CGPoint pos = playerObject.position;
pos.x+= playerVelocity.x;
playerObject.position = pos;
What I'm confused about is what exactly is happening behind the scenes here. Is my assumption above correct?
When the playerVelocity is at 150,0 and is multiplied by 0.4, does the X coordinate of the playerVelocity variable gradually reduce, i.e. 150,0 , 145,0 , 130,0 etc.. ?
If I figure this out I'll then know how my playerObject is moving.
It looks like you have a constant deceleration (.4) that is opposing motion in whatever direction you are currently traveling subtracted from the acceleration as received via the accelerometer, which is multiplied by a constant. This value is then added to your current velocity. So you are essentially adding the difference of (acceleration from accelerometer - constant deceleration) to your current velocity for each calculation.

smooth scroll/inertial scrolling/momentum scroll

I have an OpenGL ES View in Android thats controlled by a matrix for translation. Im trying to figure out a way to get a hint of momentum scrolling as seen in the google maps app or the iPhone. Thanks.
If your problem is in 2d, it is quite simple
You need to get the elapsed time in each frame
Your onTouch function will find the acceleration of your finger. I forgot the formula on how to get the acceleration from a distance. It should be the second derivative of position with a time variable. But you should always convert your deltaX, deltaY in acceleration. To make it easy you don't really need to put something accurate there. Edit: I don't know why I didn't see it but the function was all there...
acceleration.x = 2(newposition.x - position.x - speed.x * elapsedTime) / (elapsedTime * elapsedTime);
Once you have your acceleration you can set your new position with that code. This is simple physic dynamics in 2d. With your acceleration you can find your speed and with your speed you can find your next position.
speed.x = (float) (mass * acceleration.x * elapsed + speed.x);
speed.y = (float) (mass * acceleration.y * elapsed + speed.y);
position.x += mass * acceleration.x / 2 * elapsed * elapsed + speed.x * elapsed;
position.y += mass * acceleration.y / 2 * elapsed * elapsed + speed.y * elapsed;
speed.x *= friction;
speed.y *= friction;
Mass and friction will let you define how fast it goes and how fast it will slow down by itself. You probably will have to tweak the code because this dynamic isn't exactly nice if you have to have to scroll backward to slow down.
At the end of each frame, you will have to reset your acceleration to (0,0). And on each new frame after a touch even, the acceleration should be set to something. It should work very well :)
Measure the speed that the view is scrolling at.
Detect when the user stops scrolling.
Gradually decrease the speed that the scroll view is scrolling at.
Something like this:
public void redraw() {
myScrollView.ySpeed = myScrollView.lastY-myScrollView.y;
myScrollView.xSpeed = myScrollView.lastX-myScrollView.x;
if (!userIsScrolling && ySpeed > 0) {
ySpeed--;
}
if (!userIsScrolling && xSpeed > 0) {
xSpeed--;
}
myScrollView.lastY = myScrollView.y;
myScrollView.y += ySpeed;
myScrollView.lastX = myScrollView.x;
myScrollView.x += xSpeed;
}
public void userStoppedScrolling() {
userIsScrolling = false;
}

How to get colliding effect or bouncy when ball hits the track

** STILL NOT WORKING **
I am using below formula to move the ball circular, where accelX and accelY are the values from accelerometer, it is working fine.
But the problem in this code is mRadius (I fixed its value to 50), i need to change mRadius according to accelerometer values and also i need bouncing effect when it touches the track. Currently i am developing code by assuming only one ball is on the board.
float degrees = -atan2(accelX, accelY);
int x = cCentrePoint.x + mRadius * cos(degrees);
int y = cCentrePoint.y + mRadius * sin(degrees);
Here is the snap of the game i want to develop:
Balls Game http://iphront.com/wp-content/uploads/2009/12/bdece528ea334033.jpg.jpg
Updated: I am sending the updated code...
mRadius = 5;
mRange = NSMakeRange(0,60);
-(void) updateBall: (UIAccelerationValue) accelX
withY:(UIAccelerationValue)accelY
{
float degrees = -atan2(accelX, accelY);
int x = cCentrePoint.x + mRadius * cos(degrees);
int y = cCentrePoint.y + mRadius * sin(degrees);
//self.targetRect is rect of ball Object
self.targetRect = CGRectMake(newX, newY, 8, 9);
self.currentRect = self.targetRect;
static NSDate *lastDrawTime;
if(lastDrawTime!=nil)
{
NSTimeInterval secondsSinceLastDraw =
-([lastDrawTime timeIntervalSinceNow]);
ballXVelocity = ballXVelocity + (accelX * secondsSinceLastDraw)
* [self isTouchedTrack:mRadius andRange:mRange];
ballYVelocity = ballYVelocity + -(accelY * secondsSinceLastDraw)
* [self isTouchedTrack:mRadius andRange:mRange];
distXTravelled = distXTravelled + secondsSinceLastDraw
* ballXVelocity * 50;
distYTravelled = distYTravelled + secondsSinceLastDraw
* ballYVelocity * 50;
//Updating the ball rect
CGRect temp = self.targetRect;
temp.origin.x += distXTravelled;
temp.origin.y += distYTravelled;
//calculating new radius after updating ball position
int radius = (temp.origin.x - cCentrePoint.x) /
cos(degreesToRadians(degrees));
if( !NSLocationInRange(abs(radius),mRange))
{
//Colided with the tracks...Need a better logic here
ballXVelocity = -ballXVelocity;
}
else
{
// Need a better logic here
self.targetRect = temp;
}
}
[lastDrawTime release];
lastDrawTime = [ [NSDate alloc] init];
}
In the above code i have initialized mRadius and mRange(indicate track) to some constant for testing, i am not getting the moving of the ball as i expected( bouncing effect when Collided with track ) with respect to accelerometer. Help me to recognize where i went wrong or send some code snippets or links which does the similar job.
I am searching for better logic than my code, if you found share with me.
If I understand your code correctly, then the ball's position is directly controlled by the iPhone's orientation (tilt). So, tilting the iPhone to the right will place the ball at the right side of the track (3 o'clock). I believe you may want the balls acceleration (or, at least, its velocity) to be controlled. Then, you integrate the acceleration to velocity and the velocity to place, taking into account the constraints (the track walls).
The way it is set now, I don't see how you'd control more than one ball (as per the image you posted).
Then, for the bouncing effect: if you mean bouncing by the track's wall, then this will be a small modulation of the mRadius. If you mean bounce by other ball, then you'd modulate the angular position (by means of angular velocity) of the two balls to reflect the reaction.
EDIT: for integration of acceleration to velocity and then to position, for the purpose of this game, you can do with 1st order rectangular integration. Also, it will be more realistic to make the acceleration proportional to the tilt angle. Given the accel values from the iPhone itself, you can assign a 1:1 relation between the balls accel and the device reading. So, you'd like something like:
BallAccX = AccelX * Am_I_NOT_touching_a_wall_in_X_direction() * Ka
BallVelX = BallVelX + BallAccX * dT * Kv
BallPosX = BallPosX + BallVelX * dT * Kp
Note: the above formulae for velocity and position are 1st order approximation but should be sufficient for the purpose of this game.
Ka, Kv, Kp are some proportion coefficients. Choose them to make the relation between the sensed acceleration and the ball movement as you like. dT is the time difference between updates of the state of the ball. The function Am_I_NOT_touching_a_wall_in_X_direction() returns a 1 if the ball is free to move horizontally (in the direction of the tilt) and 0 otherwise.
Calculations for Y movement is symmetrical.
After trying alot I thought it is not easy to produce real time effect without using any physics engine. So its better to use BOX2d or Chipmunks or any other physics engines.