If you like this tutorial, feel free to send me a donation at baseballer1149@aol.com via paypal.
First off, the UIAccelerometer is something that a lot of apps use. It's that thing that automatically detects when the user has moved his/her iphone. It measures on 3 axis, and they are the following.
X: When the user moves iphone left/right
Y: When the user moves iphone forward/backward
Z: When the user moves the iphone up/down
Now, to use this in an application.
Go ahead and open up a new View-based application.
Lets name is accel.
Now, open up accelViewController.h and add an IBOutlet for a UILabel
quickly open up the *.m file and put in the following (underneath @implementation)
Code:
@synthesize label;
this will create getter and setter methods for changing values about our label
now, open up the .nib file for this view.
Drag on a UILabel, and in connections inspector drag from "New Referencing Outlet" to files owner, and select the label outlet.
Now, head back to the *.m file
uncomment the viewDidLoad method (towards the bottom of the file)
And inside of the viewDidLoad method, put the following:
now, you're good. One thing left to explain. UIAcceleration has 3 values to it, X, Y, and Z. In order to assure the gesture wasn't by accident, we test to see if each value is above 1.5. You can use this in numerous ways, you just have to think of creative things. Instead of buttons, sometimes think of all the other things the iphone can do, and use those (accelerometer, microphone, etc.)
Have fun and post comments if you need help
Oh, and don't forget to build-run the app!
Last edited by meowmix23F; 04-03-2009 at 03:17 PM.
Reason: Added code tags.
This looks a lot like the sample given in the Beginning iPhone Development book. The thing I'm not crazy about is how the motion detection check is performed. Each axis of the acceleration vector is examined independent of the others, which -- while adequate enough for the sake of the tutorial -- isn't the most accurate approach.
IMHO, a better (i.e. more accurate) technique involves treating the acceleration vector that is sent to the callback as, well, a vector. So, rather than testing any single axis for motion beyond a threshold, as in the original code,
I would opt for the following, which calculates the magnitude of the true (3D) acceleration vector and compares that to the threshold:
Code:
- (void)accelerometer:(UIAccelerometer *)acel didAccelerate:(UIAcceleration *)aceler
{
// note: this can be optimized by removing the sqrt() call and comparing against (threshold * threshold)
if ( sqrt(aceler.x * aceler.x + aceler.y * aceler.y + aceler.z * aceler.z) > 1.5f ) )
{
if ( [label.text isEqualToString:@"Broken"] == YES )
{
[label setText:@"Fixed"];
}
else
{
[label setText:@"Broken"];
}
}
}
While I recognize that what's most important in this tutorial is the instruction on how to set up the accelerometer to make the callbacks and how to write the callback handler, I thought it was worth pointing out how you can obtain the actual acceleration vector magnitude.
Great tutorial, many thanks. Nicely focused on the subject.
Forgive a possibly stupid question, as i am no expert in physics.
If I want to just respond to the user "shaking" the iPhone, say for dice, or like the iPod Nano does for switching to another random song, should I just check for a large difference (the delta) in the x, y, or z values ? Therefore, I should keep track of the previous values and then just check for a delta. Would there be an appropriate to check for, or maybe I should just test out different deltas and see how they work.
Great tutorial, many thanks. Nicely focused on the subject.
Forgive a possibly stupid question, as i am no expert in physics.
If I want to just respond to the user "shaking" the iPhone, say for dice, or like the iPod Nano does for switching to another random song, should I just check for a large difference (the delta) in the x, y, or z values ? Therefore, I should keep track of the previous values and then just check for a delta. Would there be an appropriate to check for, or maybe I should just test out different deltas and see how they work.
Many Thanks.
Sorry it took so long for me to respond, by the way.
To check for a light shake, just check if the absolute value of the x, y, and z properties are greater than 1.5 or 2.0. 2.0 is generally a strong shake, and 1.5 is generally a light shake.
now, open up the .nib file for this view.
Drag on a UILabel, and in connections inspector drag from "New Referencing Outlet" to files owner, and select the label outlet.
The only outlet option I have here is for "view".
I've just fallen off the iPhone turnip truck, so bear with me. Thanks.
Hm, I think I'm getting there. Now I'm hung up on a few errors:
Code:
"syntax error before ';' token:"
UIAccelerometer *accel = [[UIAccelerometer sharedAccelerometer];
accel.delegate = self;
"'didReceiveMemoryWarning' undeclared (first use in this function):"
"syntax error before '{' token:"
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
// Release anything that's not essential, such as cached data
}
Error: 'didReceiveMemoryWarning' undeclared (first use in this function)
Code:
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
// Release anything that's not essential, such as cached data
}
Error: syntax error before '{' token:
Code:
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
// Release anything that's not essential, such as cached data
}
I'm starting to think this thread isn't a good tutorial for me right now. The posted code contains typos and being a noob, I'm getting thrown off by it pretty easily.
Woops, im really sorry. You were right. I updated the post with the actual way it's supposed to be done. I was working with NSFileManager so i did that without even thinking.
Woops, im really sorry. You were right. I updated the post with the actual way it's supposed to be done. I was working with NSFileManager so i did that without even thinking.
Hi, I get 7 errors after compiling, but it are 2 different kinds of errors:
- error: syntax error before before UILabel
- error: syntax error before before '{' token
Can somebody please tell me what I am doing wrong? I think it is something with the NIB-file?
I really need this accelerovalues...
I have it compiled, and even pushed to the phone. Can it be "tested" in the simulator? In the viewDidLoad method, does your code come before or after [super viewDidLoad];? I'm assuming after.
I'm pretty much a newbie, so, following examples is how I'm learning, but, still not able to "dig out" what's going on here. Thanks! Keep up the examples.
Here is how I compute the new position of my object:
Code:
- (void) tick
{
if (gameFinished)
return;
float dTime;
CFTimeInterval time;
time = CFAbsoluteTimeGetCurrent();
dTime = time - lastTime;
float accelerationX = (accelerometerValues[1]) * dTime * 1000;
float accelerationY = (accelerometerValues[0]) * dTime * 1000;
float newX=m_TargetImgView.center.x+accelerationX;
float newY=m_TargetImgView.center.y+accelerationY;
if (newX < 0)
newX=0;
else if (newX > 480)
newX = 480;
if (newY < 0)
newY=0;
else if (newY > 320)
newY = 320;
m_myImgView.center=CGPointMake(newX,newY);
lastTime = time;
}
Thanks in advance for any help
Alx
What specifically about your code isn't working? Are you seeing any movement? Is the movement too great? Is the movement in the wrong direction? It's difficult to diagnose a problem without knowing what the symptoms are.
What specifically about your code isn't working? Are you seeing any movement? Is the movement too great? Is the movement in the wrong direction? It's difficult to diagnose a problem without knowing what the symptoms are.
Sorry, you're right, I didn't give details.
Bu I've solved my problem, so my post can be deleted now.
in the header file, and also the @property() for it.
Also, make sure you don't open up mainwindow.xib, because that's not the right file.
Is this missing from the code at the top?
Sorry another Newb here - could the original post be updated if it is.
I'm getting this error
2009-04-17 15:37:26.599 accel[1328:107] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[UIViewController _loadViewFromNibNamed:bundle:] loaded the "accelViewController" nib but the view outlet was not set.'